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

查看:29
本文介绍了何时在 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. 一个效果(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(例如向用户显示消息)
    • 和/或通过减速器(例如,保留错误计数或从状态中删除某些内容)

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

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