@ngrx/effect

前面我们提到,在 Book 的 reducer 中,并没有 Search 这个 Action 的处理,由于它需要发出一个异步的请求,等到请求返回前端,我们需要根据返回的结果来操作 store。所以,真正操作 store 的应该是 Search_Complete 这个 Action。我们在 recducer 已经看到了。

对于 Search 来说,我们需要见到这个 Action 就发出一个异步的请求,等到异步处理完毕,根据返回的结果,构造一个 Search_Complete 来将处理的结果派发给 store 进行处理。

这个解耦是通过 @ngrx/effect 来处理的。

@ngrx/effect 提供了装饰器 @Effect 和 Actions 来帮助我们检查 store 派发出来的 Action,将特定类型的 Action 过滤出来进行处理。监听特定的 Action, 当发现特定的 Action 发出之后,自动执行某些操作,然后将处理的结果重新发送回 store 中。

Book 搜索处理

以 Book 为例,我们需要监控 Search 这个 Action, 见到这个 Action 就发出异步的请求,然后接收请求返回的数据,如果在接收完成之前,又遇到了下一个请求,那么,直接结束上一个请求的返回数据。如何找到下一个请求呢?使用 skip 来获取下一个 Search Action。

源码

/src/effects/book.ts

import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/skip';
import 'rxjs/add/operator/takeUntil';
import { Injectable } from '@angular/core';
import { Effect, Actions, toPayload } from '@ngrx/effects';
import { Action } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';
import { empty } from 'rxjs/observable/empty';
import { of } from 'rxjs/observable/of'; import { GoogleBooksService } from '../services/google-books';
import * as book from '../actions/book'; /**
* Effects offer a way to isolate and easily test side-effects within your
* application.
* The `toPayload` helper function returns just
* the payload of the currently dispatched action, useful in
* instances where the current state is not necessary.
*
* Documentation on `toPayload` can be found here:
* https://github.com/ngrx/effects/blob/master/docs/api.md#topayload
*
* If you are unfamiliar with the operators being used in these examples, please
* check out the sources below:
*
* Official Docs: http://reactivex.io/rxjs/manual/overview.html#categories-of-operators
* RxJS 5 Operators By Example: https://gist.github.com/btroncone/d6cf141d6f2c00dc6b35
*/ @Injectable()
export class BookEffects { @Effect()
search$: Observable<Action> = this.actions$
.ofType(book.ActionTypes.SEARCH)
.debounceTime(300)
.map(toPayload)
.switchMap(query => {
if (query === '') {
return empty();
} const nextSearch$ = this.actions$.ofType(book.ActionTypes.SEARCH).skip(1); return this.googleBooks.searchBooks(query)
.takeUntil(nextSearch$)
.map(books => new book.SearchCompleteAction(books))
.catch(() => of(new book.SearchCompleteAction([])));
}); constructor(private actions$: Actions, private googleBooks: GoogleBooksService) { }
}

collection.ts

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/toArray';
import { Injectable } from '@angular/core';
import { Action } from '@ngrx/store';
import { Effect, Actions } from '@ngrx/effects';
import { Database } from '@ngrx/db';
import { Observable } from 'rxjs/Observable';
import { defer } from 'rxjs/observable/defer';
import { of } from 'rxjs/observable/of'; import * as collection from '../actions/collection';
import { Book } from '../models/book'; @Injectable()
export class CollectionEffects { /**
* This effect does not yield any actions back to the store. Set
* `dispatch` to false to hint to @ngrx/effects that it should
* ignore any elements of this effect stream.
*
* The `defer` observable accepts an observable factory function
* that is called when the observable is subscribed to.
* Wrapping the database open call in `defer` makes
* effect easier to test.
*/
@Effect({ dispatch: false })
openDB$: Observable<any> = defer(() => {
return this.db.open('books_app');
}); /**
* This effect makes use of the `startWith` operator to trigger
* the effect immediately on startup.
*/
@Effect()
loadCollection$: Observable<Action> = this.actions$
.ofType(collection.ActionTypes.LOAD)
.startWith(new collection.LoadAction())
.switchMap(() =>
this.db.query('books')
.toArray()
.map((books: Book[]) => new collection.LoadSuccessAction(books))
.catch(error => of(new collection.LoadFailAction(error)))
); @Effect()
addBookToCollection$: Observable<Action> = this.actions$
.ofType(collection.ActionTypes.ADD_BOOK)
.map((action: collection.AddBookAction) => action.payload)
.mergeMap(book =>
this.db.insert('books', [ book ])
.map(() => new collection.AddBookSuccessAction(book))
.catch(() => of(new collection.AddBookFailAction(book)))
); @Effect()
removeBookFromCollection$: Observable<Action> = this.actions$
.ofType(collection.ActionTypes.REMOVE_BOOK)
.map((action: collection.RemoveBookAction) => action.payload)
.mergeMap(book =>
this.db.executeWrite('books', 'delete', [ book.id ])
.map(() => new collection.RemoveBookSuccessAction(book))
.catch(() => of(new collection.RemoveBookFailAction(book)))
); constructor(private actions$: Actions, private db: Database) { }
}

See also:

@ngrx/effects

skip

takeUntil

What is the purpose of ngrx effects library?

ngRx 官方示例分析 - 6 - Effect的更多相关文章

  1. ngRx 官方示例分析 - 3. reducers

    上一篇:ngRx 官方示例分析 - 2. Action 管理 这里我们讨论 reducer. 如果你注意的话,会看到在不同的 Action 定义文件中,导出的 Action 类型名称都是 Action ...

  2. ngRx 官方示例分析 - 2. Action 管理

    我们从 Action 名称开始. 解决 Action 名称冲突问题 在 ngRx 中,不同的 Action 需要一个 Action Type 进行区分,一般来说,这个 Action Type 是一个字 ...

  3. ngRx 官方示例分析 - 1. 介绍

    ngRx 的官方示例演示了在具体的场景中,如何使用 ngRx 管理应用的状态. 示例介绍 示例允许用户通过查询 google 的 book  API  来查询图书,并保存自己的精选书籍列表. 菜单有两 ...

  4. ngRx 官方示例分析 - 4.pages

    Page 中通过构造函数注入 Store,基于 Store 进行数据操作. 注意 Component 使用了 changeDetection: ChangeDetectionStrategy.OnPu ...

  5. ngRx 官方示例分析 - 5. components

    组件通过标准的 Input 和 Output 进行操作,并不直接访问 store. /app/components/book-authors.ts import { Component, Input ...

  6. RocketMQ源码分析之从官方示例窥探:RocketMQ事务消息实现基本思想

    摘要: RocketMQ源码分析之从官方示例窥探RocketMQ事务消息实现基本思想. 在阅读本文前,若您对RocketMQ技术感兴趣,请加入RocketMQ技术交流群 RocketMQ4.3.0版本 ...

  7. Halcon斑点分析官方示例讲解

    官方示例中有许多很好的例子可以帮助大家理解和学习Halcon,下面举几个经典的斑点分析例子讲解一下 Crystals 图中显示了在高层大气中采集到的晶体样本的图像.任务是分析对象以确定特定形状的频率. ...

  8. DotNetBar for Windows Forms 12.7.0.10_冰河之刃重打包版原创发布-带官方示例程序版

    关于 DotNetBar for Windows Forms 12.7.0.10_冰河之刃重打包版 --------------------11.8.0.8_冰河之刃重打包版------------- ...

  9. DotNetBar for Windows Forms 12.5.0.2_冰河之刃重打包版原创发布-带官方示例程序版

    关于 DotNetBar for Windows Forms 12.5.0.2_冰河之刃重打包版 --------------------11.8.0.8_冰河之刃重打包版-------------- ...

随机推荐

  1. Mysql使用alias 防止对数据的误操作

    在我们操作数据库的时候,尤其是执行,update,delete操作的时候,都存在着误操作的风险,今天发现一种方法,能避免这一问题,就是使用Mysql的alias . 1.查看Mysql帮助 #mysq ...

  2. 怎么为WebStorm更换主题 修改字体样式

    这篇文章主要用于帮助大家解决怎么为webstorm换theme. 首先,到选择一个自己喜欢的皮肤,Webstorm皮肤网址: http://phpstorm-themes.com/ 然后,选中你喜欢的 ...

  3. Zabbix Agent端配置文件说明

    Zabbix Agent端配置文件说明 由于工作中经常接触到zabbix,所以将agent配置整理一下,方便日常查看. # This is a config file for the Zabbix a ...

  4. 浅析mongodb

    当爬取数据时候,我们可能需要缓存大量的数据,但是又无须任何复杂的连接操作,因此我们将选用NoSQL数据库,这种数据库比传统的关系型数据库更易于操作,这里我想主要说一下目前非常流行的MongoDB作为缓 ...

  5. 日志采集框架Flume以及Flume的安装部署(一个分布式、可靠、和高可用的海量日志采集、聚合和传输的系统)

    Flume支持众多的source和sink类型,详细手册可参考官方文档,更多source和sink组件 http://flume.apache.org/FlumeUserGuide.html Flum ...

  6. sso示例代码

    个人写的一个关于在ASP.NET 中如何实现SSO单点登录,这可能也是.NET实现大型互联网项目的第一步要解决的问题.已经放到GitHub上供大家参考.https://github.com/bidia ...

  7. C#学习笔记-策略模式

    题目:做一个商场收银的小程序,可能会出现的情况包括:正常收费,九折优惠,七折优惠,满300减50等各种不同随时会变化的优惠活动. 界面如下: 分析: 首先我们对于收钱写一个父类CashSuper.这个 ...

  8. Codeforces #452 Div2 F

    #452 Div2 F 题意 给出一个字符串, m 次操作,每次删除区间 \([l,r]\) 之间的字符 \(c\) ,输出最后得到的字符串. 分析 通过树状数组和二分,我们可以把给定的区间对应到在起 ...

  9. SQL server学习(二)表结构操作、SQL函数、高级查询

    数据库查询的基本格式为: select ----输出(显示)你要查询出来的值 from -----查询的依据 where -----筛选条件(对依据(数据库中存在的表)) group by ----- ...

  10. AtCoder Grand Contest 019

    最近比较懒,写了俩题就跑了 A - Ice Tea Store 简化背包 #include<cstdio> #include<algorithm> using namespac ...