[Angular 2] Handle Reactive Async opreations in Service
2016-06-24 03:02
711 查看
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:
In this ItemService, we get Items from store:
To change state, it flows the style that
Call the backend
if success generate action
dispatch the action
In the controller:
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:
We base on async pipe to update the dom:
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.
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.
相关文章推荐
- H5、React Native、Native应用对比分析
- React Native入门学习笔记三(JSX语法)
- reactjs+echarts实现绘图
- CocoaPods安装第三方SDK报错[!] The dependency `ReactiveCocoa (~> 4.1.0)` is not used in any concrete target.
- reactiveCocoa实践二
- 转 : React Native 开发之 IDE 选型和配置
- React之JSX入门
- React基础语法学习
- ReactiveCocoa
- 旅行喵 React Native 技术实践
- React Native入门学习笔记二(环境搭建Mac+ios)
- Cordova VS React Native 谁是未来? - b
- ACE - Reactor模式源码剖析及具体实现(大量源码慎入)
- ReactiveCocoa的学习
- 配置react+webpack+es6中的一些教训
- 学习react
- React-Native学习指南
- ReactJs实战感悟
- ReactNative学习笔记1 Flexbox布局
- reactiveCocoa实践一