何时在angular2中使用ngrx/effect [英] When to use ngrx/effect in angular2

查看:62
本文介绍了何时在angular2中使用ngrx/effect的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与api通讯的anuglar2项目.最近,我决定集成ngrx/store来维护组件的状态,并遵循dump-smart组件架构.但是随后,我继续阅读有关可以在api请求中使用的ngrx/effect的信息.

I have an anuglar2 project that communicates with an api. Recently, I decided to integrate ngrx/store to maintain the state of the components, and follow the dump-smart component architecture. But then while moving on, I read about ngrx/effect which can be used upon the api requests.

我的问题来了,为什么我应该使用ngrx/effect库,而不是只从容器组件中调用服务中的相应函数来执行api请求,并执行成功的派遣操作以将返回的值保存在我的商店中

And here my question comes, why should I use the ngrx/effect library, over just calling the corresponding function in my service from my container component to perform the api request and on success dispatch action to save the returned values in my store.

推荐答案

如果情况如此简单,则不需要effect.此外,effect本身只不过是调用您的服务方法而已.

If your case stays that simple, then you won't need an effect for it. Besides, the effect itself will do not much more than calling your service-method.

简而言之:如果您的项目很小,并且没有很多功能,那只会导致您编写更多代码.

In short: If you project is very small and without many features, it will just cause you to write more code.

如果您的项目很大,它将帮助您构建数据流和项目组件.

If you project is large, it will help you structure your data-flows and project-components.

当您要基于其他动作触发一个动作(使用英语口语时,您将其称为 side- effect ),或者当您想要添加通用错误处理或记录.

When you want to trigger an action based on another action(in spoken english you would call this a side-effect) or when you want to add a generic error-handling or maybe a logging.

effect的工作方式:effect侦听任何已定义的动作(例如 LoadDataAction ),然后进行一些处理并返回所有随后处理的动作由商店分发给减速器或其他effect.

The way an effect works: The effect listens for any defined action(s) (e.g. LoadDataAction), then does some processing and returns any action(s) that are then processed by the store and distributed to a reducer or some other effect.

示例:

  1. LoadDataAction 已分派
  2. 触发了effect( loadData $ )
  3. loadData $ -effect调用数据服务
  4. 加载数据失败
  5. loadData $ -effect返回 LoadDataFailureAction
  1. LoadDataAction is dispatched
  2. an effect(loadData$) is triggered
  3. the loadData$-effect calls the data-service
  4. loading the data fails
  5. the loadData$-effect return a LoadDataFailureAction

ngrx处理动作...

ngrx processes the action...

  1. LoadDataFailureAction 可能由以下人员获取:
    • 记录器效果(例如,将消息发送到服务器)
    • 通过ui-notification-effect(例如向用户显示消息)
    • 和/或由化简器(例如,保留错误计数或从状态中删除某些内容)
  1. the LoadDataFailureAction might be picked up by:
    • a logger-effect(e.g. sends message to a server)
    • by an ui-notification-effect(e.g. displays message to user)
    • and/or by a reducer(e.g. persists the error-count or deletes something from the state)

这篇关于何时在angular2中使用ngrx/effect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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