[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 ...
随机推荐
- YCbCr
http://blog.csdn.net/shizhixin/article/details/4494358 YCbCr 则是在世界数字组织视频标准研制过程中作为ITU - R BT1601 建议的一 ...
- delphi中formatFloat代码初探(在qt下实现floatformat的函数)
由于项目需要,需要在qt下实现floatformat的函数.之前写过一个,但是写得不好.决定重新写一个,参考delphi xe2下的实现.把xe2下的相关代码都看了一遍,xe2的代码思路在这里贴出来. ...
- VCL+FMX 双剑合壁编程
VCL 是经典,FMX 是新生,新生事物总会带来一些好玩新奇的东西.舍弃经典是浪费,不了解新生事物是等死,那么我们来一个二合一双剑合壁又如何呢? 要双剑合壁,就得投些机,取些巧.由于 Delphi / ...
- iOS,Android网络抓包教程之tcpdump
现在的移动端应用几乎都会通过网络请求来和服务器交互,通过抓包来诊断和网络相关的bug是程序员的重要技能之一.抓包的手段有很多:针对http和https可以使用Charles设置代理来做,对于更广泛的协 ...
- jstring 和char 之间的转换方法
//jstring to char* char* jstringTostring(JNIEnv* env, jstring jstr) { char* rtn = NULL; jclass clsst ...
- 【HDOJ】1018 Big Number
数学题,还是使用log避免大数,但是不要忘记需要+1,因为0也是1位,log(100)= 2,但却是3位. #include <stdio.h> #include <math.h&g ...
- HTML颜色编码
Web安全色 #000000 #000033 #000066 #000099 #0000CC #0000FF #003300 #003333 #003366 #003399 #0033CC #0033 ...
- Emeditor所有快捷键操作
新建文本 Ctrl+N 创建一个新的文本文件. 打开 Ctrl+O 打开一个已存在的文件. 保存 Ctrl+S 保存当前文件. 重新 ...
- jdk1.7升级到jdk1.8后出错: [ERROR] javadoc: warning - Multiple sources of package comments found for package
from: http://blog.joda.org/2014/02/turning-off-doclint-in-jdk-8-javadoc.html [ERROR] javadoc: warnin ...
- bat中的连接符
& [...] command1 & command2 用来分隔一个命令行中的多个命令.Cmd.exe 运行第一个命令,然后运行第二个命令. && [...] comm ...