1

在 angular-redux 中调度操作时如何发送有效负载?我在任何地方都找不到它的解释,无论是在官方教程中,还是在 API-Docs 中。

“Action”类有一个属性“type”,但没有属性“payload”。

API 文档:https ://angular-redux.github.io/store/

4

2 回答 2

0

我的方法与 @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
  };
}

减速器/约会.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 操作: 约会.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);
  }
}
于 2019-05-01T19:31:34.223 回答
0

我现在所做的不是创建 Action 类型的动作,而是创建了 AnyAction 类型的动作。

AnyAction 扩展了 Action 并具有附加属性“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 };
}

现在我可以使用有效负载作为参数调用调度:

this.ngRedux.dispatch(this.myActions.myAction(payload));

并在我的商店中使用它:

case MyActions.MY_ACTION: {
    // payload
    let payload = action['extraProps'];
}

但这是在 angular-redux 中通过操作发送有效负载的正确方法吗?

于 2018-01-26T13:19:30.220 回答