[Angular 2] Handle Reactive Async opreations in Service
When you use ngrx/store and you want to fire a service request. When it sucessfully return the response, you need to dispatch action to tell the store update.
So one pattern can be considered to follow is:
import {Http, Headers} from '@angular/http';
import {Injectable} from '@angular/core';
import {Store} from '@ngrx/store';
import {Observable} from "rxjs/Observable";
import 'rxjs/add/operator/map';
import {AppStore} from '../models/appstore.model';
import {Item} from '../models/item.model';
const BASE_URL = 'http://localhost:3000/items/';
const HEADER = { headers: new Headers({ 'Content-Type': 'application/json' }) };
@Injectable()
export class ItemsService {
items: Observable<Array<Item>>;
constructor(private http: Http, private store: Store<AppStore>) {
this.items = store.select('items');
}
loadItems() {
this.http.get(BASE_URL)
.map(res => res.json())
.map(payload => ({ type: 'ADD_ITEMS', payload }))
.subscribe(action => this.store.dispatch(action));
}
saveItem(item: Item) {
return (item.id) ? this.updateItem(item) : this.createItem(item);
}
createItem(item: Item) {
return this.http.post(`${BASE_URL}`, JSON.stringify(item), HEADER)
.map(res => res.json())
.do(payload => {
const action = { type: 'CREATE_ITEM', payload };
this.store.dispatch(action)
});
}
updateItem(item: Item) {
return this.http.put(`${BASE_URL}${item.id}`, JSON.stringify(item), HEADER)
.do(action => this.store.dispatch({ type: 'UPDATE_ITEM', payload: item }));
}
deleteItem(item: Item) {
return this.http.delete(`${BASE_URL}${item.id}`)
.do(action => this.store.dispatch({ type: 'DELETE_ITEM', payload: item }));
}
}
In this ItemService, we get Items from store:
items: Observable<Array<Item>>;
constructor(private http: Http, private store: Store<AppStore>) {
this.items = store.select('items');
}
To change state, it flows the style that
- Call the backend
- if success generate action
- dispatch the action
createItem(item: Item) {
return this.http.post(`${BASE_URL}`, JSON.stringify(item), HEADER)
.map(res => res.json())
.do(payload => {
const action = { type: 'CREATE_ITEM', payload };
this.store.dispatch(action)
});
}
In the controller:
saveItem(item: Item) {
this.itemsService.saveItem(item)
.subscribe( (res) => {this.resetItem()},
(err) => {console.error(err)},
() => {console.info("Completed")});
If you notice, in loadItems, I didn't' use do() to dispatch action and subscribe in controller, instead I subscribe in service, this is because in controller, it doesn't expect receive anything from service:
constructor(private itemsService: ItemsService,
private gadgetService: GadgetService,
private store: Store<AppStore>) {
this.items = itemsService.items;
itemsService.loadItems();
}
We base on async pipe to update the dom:
<items-list [items]="items | async"
(selected)="selectItem($event)" (deleted)="deleteItem($event)">
</items-list>
But for createItem, deleteItem, we use do() to dispatch action and subscribe action, this is because we want to confrim weather it successfully updated, then we want to clear the input fields.
[Angular 2] Handle Reactive Async opreations in Service的更多相关文章
- [Angular Testing] Unit Testing -- Test component and service.
Recommend to use angular-cli to generate component and service, so we can get testing templates. ng ...
- angular ajax的使用及controller与service分层
一个简单的例子,控制层:.controller('publishController',['$scope','publishService', function($scope,publishServi ...
- ionic准备之angular基础———服务provider 和 factory和service(9)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- [Angular] Bind async requests in your Angular template with the async pipe and the "as" keyword
Angular allows us to conveniently use the async pipe to automatically register to RxJS observables a ...
- [Angular] Wrap a third party lib into service
- Angular service, 服务
早上开车上班, 发现车快没油了, 于是拐进加油站. 有一辆出租车也在加油.. Angular service在一个应用里是以单例形式存在的. 这个单例的实例是由service factory( ...
- angular 服务 service factory provider constant value
angular服务 服务是对公共代码的抽象,由于依赖注入的要求,服务都是单例的,这样我们才能到处注入它们,而不用去管理它们的生命周期. angular的服务有以下几种类型: 常量(Constant): ...
- [Angular Directive] Build a Directive that Tracks User Events in a Service in Angular 2
A @Directive is used to add behavior to elements and components in your application. This makes @Dir ...
- [Angular Directive] Create a Template Storage Service in Angular 2
You need to define a <template> to be able to use it elsewhere in your app as a TemplateRef. Y ...
随机推荐
- 命令行静态编译QT程序
在.pro文件里加上(非必须)CONFIG += static release windows 静态库必须放在这个路径:C:\Qt\Qt5.3.2_static\bin\qmake -makefile ...
- Autodesk 2014全套密钥
AUTODESK 2014通用安装序列号: 666-69696969 667-98989898 400-45454545 066-66666666 AUTODESK 2014全系列产品密钥 001F1 ...
- vi编辑器的三种模式
1.命令模式(command mode)—执行命令 在该模式中,可以输入命令来执行许多种功能.控制屏幕光标的移动,字符.字或行的删除,移动复制某区段及进入Insert mode下,或者到 last l ...
- ORA-28001: the password has expired
大早上正式库提示: Oracle提示错误消息ORA-28001: the password has expired 解决办法: 1.利用SYSDBA权限登陆: 2.查看账户信息:select user ...
- css3动画(transition)属性探讨
在webapp引用开发中经常会用到css3动画效果,下面我们就一起探讨一下这个属性的使用. 在哪里定义动画效果? css3动画一般通过鼠标事件或者说状态定义动画,通常我们可以用CSS中伪类和js中的鼠 ...
- -_-#【减少 DOM 访问】“离线”更新节点,再将它们添加到树中
Minimize DOM Access javascript 之 DOM 优化 <!DOCTYPE html> <html> <head> <meta cha ...
- 使用 HTML5、CSS3 和 MathML 在 EPUB 3 中制作版式丰富的出版物
探索用于高级排版和印刷的新一代开放电子书标准 EPUB 3.0 是最新的行业标准 XML 电子书格式,它采用了 HTML5 和 CSS3,因而融入了现代 Web 技术.它重点关注 XML 驱动的工具包 ...
- BrnShop开源网上商城第六讲:扩展视图功能
在正式讲解扩展视图功能以前,我们有必要把视图的工作原理简单说明下.任何一个视图都会被翻译成一个c#类,并保存到指定的位置,然后被编译.这也就是为什么能在视图中包含c#代码片段的原因.下面我们通过一个项 ...
- Shell 脚本编程
Shell 两个数据比较取差异 flag=0 local array1=("a" "b") local array2=("a" " ...
- Tomcat启动时为什么要配置CATALINA_HOME环境变量??
CATALINA_HOME的值被设为Tomcat的安装目录,如果环境变量CATALINA_HOME已经存在,则通过这个环境变量调用bin目录下的“catalina.bat start”命令 1.Tom ...