[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 ...
随机推荐
- flash 类和对象的关系
每个具体的对象后面都隐藏着抽象的类. flash 中as3.0中所有的类,都是为了创建对象所用的.反过来,所创建的任何具体对象都隐藏着抽象的类. 类可以把它看做函数,类的属性是函数的数据,类的方法是函 ...
- ANDROID_MARS学习笔记_S01原始版_017_绑定SERVICE
一.流程 1.编写service,重写onBind(Intent intent),返回自定义的Binder 2.自写义Binder,提供一个可访问的方法,以传递数据 3.点击界面按钮会开启servic ...
- 第一章 USB Type C的基本原理
图 1: USB Type C接头外形 USB Type C(简称USB-C)的基本特性: 1. 接口插座的尺寸与原来的Micro USB规格一样小,约为8.3mm X 2.5mm 2. 可承受1万次 ...
- 为什么要重写equals()方法与hashCode()方法
在java中,所有的对象都是继承于Object类.Ojbect类中有两个方法equals.hashCode,这两个方法都是用来比较两个对象是否相等的. 在未重写equals方法我们是继承了object ...
- jQuery功能一览
// Hello world!"); }); $("#btn5").click(function(){ $("#test5").val("D ...
- hadoop mapreduce核心功能描述
核心功能描述 应用程序通常会通过提供map和reduce来实现 Mapper和Reducer接口,它们组成作业的核心. Mapper Mapper将输入键值对(key/value pair)映射到一组 ...
- 教程 打造OS X Mavericks原版 EFI Clover 引导安装
自从 Mavericks 10.9 发布DP版到现在的GM版以来,以前Clover引导原版InstallESD.dmg方式安装原版的方法已经不能使用,而且已经不能引导安装了,所以从GM版发布以前,终于 ...
- Win32下 Qt与Lua交互使用(二):在Lua脚本中使用Qt类
话接上篇.成功配置好Qt+Lua+toLua后,我们可以实现在Lua脚本中使用各个Qt的类.直接看代码吧. #include "include/lua.hpp" #include ...
- SharePoint 2010 master page 控件介绍(2):ribbon (一同事读听着像泪奔)
转:http://blog.csdn.net/lgm97/article/details/6409208 <!-- ===== 开始Ribbon ======================= ...
- HTML特殊字符大全
特殊符号 命名实体 十进制编码 特殊符号 命名实体 十进制编码 ! ! " " " # # $ $ % % & & & ' ...