在Angular应用程序中向NGRX操作添加与服务相关的逻辑 [英] Adding service dependent logic to NGRX actions in an Angular application

查看:53
本文介绍了在Angular应用程序中向NGRX操作添加与服务相关的逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的动作文件:

  export枚举ActionTypes {FailureAction ='失败动作',}导出类FailureAction实现Action {只读类型= ActionTypes.FailureAction;构造函数(公共有效载荷:任意){}}导出类型ActionTypes = FailureAction; 

我想在 FailureAction 类中添加一些逻辑,以便每当调用此动作时,我们就调用一个服务来决定如何显示错误(唯一的参数是代码).我创建了一个在构造函数中具有code参数并使用在应用程序模块中定义的依赖项注入器的类(

这甚至是我尝试做的可行方式吗?还有其他建议吗?

解决方案

动作类中不应包含特殊逻辑.该操作只是通过框架传递的数据有效负载.

有两种方法(据我所知)可以处理动作:

  1. Reducer 函数使用一个动作和一个状态来产生另一个状态
  2. 效果监听一个动作,执行一些副作用操作,然后生成一个不同的动作

如果需要基于操作执行某些操作(例如,从服务器或本地存储中查找数据),则可以使用效果.您的流程可能看起来像这样:

发生错误->调度新的错误操作(错误代码)

错误操作->错误处理效果(查找错误代码)->新的错误消息加载操作

错误消息加载操作->错误视图缩减器->出现错误消息的新视图状态

效果是可注射的服务,可以引用和使用其他服务.

请查看 @ ngrx/effects 的文档: https://ngrx.io/guide/effects

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?

解决方案

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

这篇关于在Angular应用程序中向NGRX操作添加与服务相关的逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆