1

有很多文章推荐使用 ngrx/effects 来处理异步操作,例如 http REST 调用。为什么我们不能使用常规服务来进行 http 调用,然后获取该 http 调用的结果并调度一个动作,而不是使用效果?这不是简化事情吗?

4

2 回答 2

1

You can perfectly use a regular service and then dispatch an action, like this on a component.

this.store.dispatch({
   type: "SAVE_DATA",
   payload: data
});
this.saveData(data) // POST request to server
   .map(res => this.store.dispatch({type: "DATA_SAVED"}))
   .subscribe()

@ngrx/effect just abstracts this logic away from the component. By doing this with a functional programmic aproach (pure functions), code remains very easy to test.

I really recommend reading this article, since there are many solutions to problems that abuse effects

Post

于 2018-11-29T17:15:17.723 回答
0

使用 ngrx/effects 比使用 service 进行 http 调用然后获取结果并调度操作更简单。如下

  1. 效果为服务层提供抽象。我们的组件不需要知道 services(http) 层。组件只会派发动作来完成任务。

  2. 由于效果基本上是服务,因此代码编写一次并重复使用多次。

于 2018-01-10T09:41:14.680 回答