Adding service dependent logic to NGRX actions in an Angular application

瘦欲@ 提交于 2021-01-29 04:46:09

问题


I have an actions file like this:

export enum ActionTypes {
  FailureAction = 'Failure action',
}

export class FailureAction implements Action {
  readonly type = ActionTypes.FailureAction;

  constructor(public payload: any) { }
}

export type ActionTypes = FailureAction;

I want to add some logic in the FailureAction class so that whenever this action gets called, we call a service that decides how to show an error (the only parameter is a code). I created a class that has the code parameter in the constructor and uses a dependency injector defined in the app module (Inject a service manually) to get the service needed. Then I extended the FailureAction with the newly made class and called super() with the code parameter in the constructor. When I dispatch the FailureAction the console gets bombarded with errors and crashes the whole application.

Is this even doable the way I'm trying to do it? Any alternative suggestions?


回答1:


Action classes should not have special logic in them. The action is just a data payload that is getting passed around through the framework.

There are two ways (that I know of offhand) to handle actions:

  1. A Reducer function uses an Action and a State to produce another State
  2. An Effect listens for an Action, performs some side-effect operation, then produces a different Action

If you need to perform some operation based on an action (for example, looking up data from the server or local storage), you could use an Effect. You might have a flow that looks something like this:

Error happens -> dispatch new error action (error code)

Error action -> Error handling effect (look up error code) -> new error message loaded action

Error message loaded action -> error view reducer -> new view state with error message

Effects are injectable services, which may reference and use other services.

Have a look at the documentation for @ngrx/effects: https://ngrx.io/guide/effects



来源:https://stackoverflow.com/questions/64488283/adding-service-dependent-logic-to-ngrx-actions-in-an-angular-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!