ngRx 官方示例分析 - 6 - Effect
@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:
What is the purpose of ngrx effects library?
ngRx 官方示例分析 - 6 - Effect的更多相关文章
- ngRx 官方示例分析 - 3. reducers
上一篇:ngRx 官方示例分析 - 2. Action 管理 这里我们讨论 reducer. 如果你注意的话,会看到在不同的 Action 定义文件中,导出的 Action 类型名称都是 Action ...
- ngRx 官方示例分析 - 2. Action 管理
我们从 Action 名称开始. 解决 Action 名称冲突问题 在 ngRx 中,不同的 Action 需要一个 Action Type 进行区分,一般来说,这个 Action Type 是一个字 ...
- ngRx 官方示例分析 - 1. 介绍
ngRx 的官方示例演示了在具体的场景中,如何使用 ngRx 管理应用的状态. 示例介绍 示例允许用户通过查询 google 的 book API 来查询图书,并保存自己的精选书籍列表. 菜单有两 ...
- ngRx 官方示例分析 - 4.pages
Page 中通过构造函数注入 Store,基于 Store 进行数据操作. 注意 Component 使用了 changeDetection: ChangeDetectionStrategy.OnPu ...
- ngRx 官方示例分析 - 5. components
组件通过标准的 Input 和 Output 进行操作,并不直接访问 store. /app/components/book-authors.ts import { Component, Input ...
- RocketMQ源码分析之从官方示例窥探:RocketMQ事务消息实现基本思想
摘要: RocketMQ源码分析之从官方示例窥探RocketMQ事务消息实现基本思想. 在阅读本文前,若您对RocketMQ技术感兴趣,请加入RocketMQ技术交流群 RocketMQ4.3.0版本 ...
- Halcon斑点分析官方示例讲解
官方示例中有许多很好的例子可以帮助大家理解和学习Halcon,下面举几个经典的斑点分析例子讲解一下 Crystals 图中显示了在高层大气中采集到的晶体样本的图像.任务是分析对象以确定特定形状的频率. ...
- DotNetBar for Windows Forms 12.7.0.10_冰河之刃重打包版原创发布-带官方示例程序版
关于 DotNetBar for Windows Forms 12.7.0.10_冰河之刃重打包版 --------------------11.8.0.8_冰河之刃重打包版------------- ...
- DotNetBar for Windows Forms 12.5.0.2_冰河之刃重打包版原创发布-带官方示例程序版
关于 DotNetBar for Windows Forms 12.5.0.2_冰河之刃重打包版 --------------------11.8.0.8_冰河之刃重打包版-------------- ...
随机推荐
- oracle 处理时间和金额大小写的相关函数集合
CREATE OR REPLACE FUNCTION MONEY_TO_CHINESE(MONEY IN VARCHAR2) RETURN VARCHAR2 IS C_MONEY ); M_STRIN ...
- Javascipt数组
Javascipt数组 在Javascript中数组的做用是:使用单独的变量名来储存一系列的值. 数组只有一个属性,就是length,length表示的数组所占内存空间的数目. <!DOCTYP ...
- Head First设计模式之模板方法模式
一.定义 在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中,使得子类可以不改变算法结构的情况下,重定义该算法中的某些特定步骤. 比较通俗的说法,子类决定如何实现算法中的某些步骤,比如两个一连串 ...
- dotnet core 自定义配置文件
首先添加一个.json 文件,比如 setting.json 文件内容如下,记得把文件设置为“复制到输出目录” { "ConfigSetting": { "XXXName ...
- TurnipBit:和孩子一起动手DIY“滚动”的生日礼物
当孩子的生日来临之时,做父母的总是会为该为孩子准备什么礼物而烦恼.下面就教家长朋友们利用TurnipBit开发板DIY一份"特殊"的生日礼物,不仅能增加与孩子的互动性还能提升孩子在 ...
- Hadoop源码篇--Client源码
一.前述 今天起剖析源码,先从Client看起,因为Client在MapReduce的过程中承担了很多重要的角色. 二.MapReduce框架主类 代码如下: public static void m ...
- Javascript一句代码实现JS字符串去除重复字符
需求: 原字符串:abcdabecd 去重后字符串:abcde JS字符串去重,一个简单需求,网上找案例发现都是一大堆代码,对于强迫症的我 实再无法忍受,于是自己手动写出一段代码,完美解决该问题. 代 ...
- Java框架之Mybatis(一)
一.Mybatis 简介 Mybatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改 ...
- easyHOOK socket send recv
代码比较简单,就不做注释了. 包含一个sockethookinject.DLL 和sockethook.exe 有一点不清楚, SetExclusiveACL可以添加当前线程的hook, 但是eas ...
- .net整理
CLR via C# 1 关于CLI,CTS,CLS,CIL,.Net Framework,CLR,FCL图 CLI:Common Language Infrastructure,是公共语言架构: C ...