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_冰河之刃重打包版-------------- ...
随机推荐
- K:HashMap中hash函数的作用
在分析了hashCode方法和equals方法之后,我们对hashCode方法和equals方法的相关作用有了大致的了解.在通过查看HashMap类的相关源码的时候,发现其中存在一个int has ...
- Git操作流程,基本命令演示
任务列表: 有一个中央库Center,和三个工作站A,B,C. 初始化时,代码存放在中央库中,A,B,C三个工作站开始工作之前都要首先从中央库克隆一份代码到本地. 第一个任务:A和B合作修复一个缺陷, ...
- 中文代码示例之Vuejs入门教程(一)
原址: https://zhuanlan.zhihu.com/p/30917346 为了检验中文命名在主流框架中的支持程度, 在vuejs官方入门教程第一部分的示例代码中尽量使用了中文命名. 所有演示 ...
- 基于2-channel network的图片相似度判别
一.相关理论 本篇博文主要讲解2015年CVPR的一篇关于图像相似度计算的文章:<Learning to Compare Image Patches via Convolutional Neur ...
- java.lang.Exception: 资源处理失败,失败原因:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column '?????‰' in 'where clause'
1:Unknown column '?????‰' in 'where clause',这个问题,百度一搜,挺多的,但是貌似好像没有解决我的问题.贴一下我是如何拼接sql的.解决这个sql拼接bug的 ...
- 【三分法】hdu2438 Turn the corner
Problem Description Mr. West bought a new car! So he is travelling around the city.One day he comes ...
- SLAVE为什么一直不动了
导读 遇到SLAVE延迟很大,binlog apply position一直不动的情况如何排查? 问题描述 收到SLAVE延迟时间一直很大的报警,于是检查一下SLAVE状态(无关状态我给隐去了): ...
- CVE-2017-8464复现 (远程快捷方式漏洞)
我们的攻击机IP是192.168.222.133 目标机IP是192.168.222.132 我们首先生成一个powershell msfvenom -p windows/x64/meterprete ...
- TagHelper+Layui封装组件之Radio单选框
TagHelper+Layui封装组件之Radio单选框 标签名称:cl-radio 标签属性: asp-for:绑定的字段,必须指定 asp-items:绑定单选项 类型为:IEnumerable& ...
- poj 3261
Milk Patterns Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 13249 Accepted: 5894 Ca ...