[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 ...
随机推荐
- javaweb学习总结(三十七)——获得MySQL数据库自动生成的主键
测试脚本如下: 1 create table test1 2 ( 3 id int primary key auto_increment, 4 name varchar(20) 5 ); 测试代码: ...
- html5 高级动画精灵
<!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8& ...
- Python sh库学习 上篇
官方文档有句话"allows you to call any program",并且:helps you write shell scripts in Python by givi ...
- libvlc 双击,鼠标事件消息响应
基于vlc 2.1 动态库实现接收双击消息的接收,使双击vlc播放画面可以全屏显示. 需要其他版本的vlc可以与我联系(有偿进行修改) 下载地址:http://download.csdn.net/de ...
- wzplayer for android V1.6.1 (支持音视频加密播放)
1.更新 2013-11-25: 1.6.1 修复1.6.0版本对rk版本的支持. 以往版本: 1.6.0 1)1.6.0修改了所有默认音频渲染使用AudioTrack输出,这样只要不播放视频,能支持 ...
- Oracle系列之权限
涉及到表的处理请参看原表结构与数据 Oracle建表插数据等等 赋予权限:前三个要在管理员权限用户下进行操作 方法1: grant dba to db_user;--赋予用户数据库管理权限 方法2: ...
- .NET程序内,访问私有或者保护成员的技巧
如果是C++,我们可以计算对象内成员的位置,然后偏移指针以访问类型的所有非公开成员.但是.NET对象完全受GC管理,地址根本无法得到,并且也无法通过指针调用方法. 当然... 这是一种很不值得推荐的技 ...
- 【转】 Xcode基本操作 -- 不错
原文网址:http://blog.csdn.net/phunxm/article/details/17044337 1.Xcode IDE概览 说明:从左到右,依次是“导航窗格(Navigator)- ...
- 【转】Ubuntu安装基础教程
原文网址:http://teliute.org/linux/Ubsetup/lesson23/lesson23.html 二十三.安装Ubuntu14.04 返回目录 下一课 14.04 版安装与前面 ...
- WebService优点和缺点小结
最近做的几个项目都用到了webservice,通过自己的实践和网上资料的汇总,现在做个小结: 当前WebService是一个热门话题.但是,WebService究竟是什么?,WebSer ...