在angular-redux中调度操作时,如何发送有效负载?我在任何地方都找不到它的解释,无论是在官方教程中,还是在API-Docs中。
类“Action”具有属性“type”,但没有属性“payload”。
发布于 2018-01-26 21:19:30
我现在所做的是创建AnyAction类型的操作,而不是创建操作类型。
AnyAction扩展了操作,并且有一个额外的属性'extraProps':
export interface AnyAction extends Action {
// Allows any extra properties to be defined in an action.
[extraProps: string]: any;
}这样我就可以将有效负载添加到我的操作声明中:
myAction(payload: any): AnyAction {
return { type: MyActions.MY_ACTION, extraProps: payload };
}现在,我可以使用有效负载作为参数来调用dispatch:
this.ngRedux.dispatch(this.myActions.myAction(payload));并在我的商店中使用它:
case MyActions.MY_ACTION: {
// payload
let payload = action['extraProps'];
}但这是在angular-redux中发送带有action的有效负载的正确方式吗?
发布于 2019-05-02 03:31:34
我的方法类似于@user1337,但有更多的类型强制:
redux-actions/appointment.ts
import { Action } from '@ngrx/store';
export enum ActionTypes {
SetStartTime = 'Set Start Time',
SetEndTime = 'Set End Time'
}
interface SetStartTime extends Action {
readonly type: ActionTypes;
readonly startTime: Date;
}
interface SetEndTime extends Action {
readonly type: ActionTypes;
readonly endTime: Date;
}
export interface AppointmentActions extends
SetStartTime,
SetEndTime {}
export function setStartTime(startTime: Date): SetStartTime {
return {
type: ActionTypes.SetStartTime,
startTime
};
}
export function setEndTime(endTime: Date): SetEndTime {
return {
type: ActionTypes.SetStartTime,
endTime
};
}reducers/appointment.ts
import { ActionTypes, AppointmentActions } from '../redux-actions/appointment.ts';
interface AppointmentState {
startTime: Date;
endTime: Date;
}
export const initialState: AppointmentState = {
startTime: null,
endTime: null
};
export function appointmentReducer(state = initialState, action: AppointmentActions): AppointmentState {
switch (action.type) {
case ActionTypes.SetStartTime:
return {
...state,
startTime: action.startTime
};
case ActionTypes.SetEndTime:
return {
...state,
endTime: action.endTime
};
default:
return state;
}
}此解决方案使您现在可以在reducer和redux操作中使用类型强制和智能感知。
因此,现在发送redux操作:appointment.component.ts
import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { appointmentReducer as appointment } from '../reducers/appointment';
import { setStartTime, setEndTime } from '../redux-actions/appointment';
@Component({
selector: 'app-appointment-component',
templateUrl: './appointment.component.html',
styleUrls: ['./appointment.component.css'],
})
export class AppointmentComponent {
....
constructor(private store: Store<{ appointment }>) {
...
}
setStartTime(startTime: Date) {
this.store.dispatch(setStartTime(startTime);
}
}https://stackoverflow.com/questions/48461277
复制相似问题