问题
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:
- A Reducer function uses an Action and a State to produce another State
- 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