[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 ...
随机推荐
- Java异常处理之throws抛出异常
package com.test; import java.io.FileReader; public class Test2 { public static void main(String[] a ...
- poj3264Balanced Lineup(RMQ)
http://poj.org/problem?id=3264 RMQ讲解 http://dongxicheng.org/structure/lca-rmq/ j = log2K dp[i][j] = ...
- bzoj2753
第一问dfs不说 第二问很容易让人想到最小树形图,但是我不会,而且时间复杂度也不允许 还有什么不同的方法呢? 首先想到的是prim的思想,设根节点已经确定,其他点未确定 我们就不断从已确定的点延伸,找 ...
- BZOJ_1601_[Usaco2008_Oct]_灌水_(最小生成树_Kruskal)
描述 http://www.lydsy.com/JudgeOnline/problem.php?id=1601 有\(n\)个田地需要灌溉,每个田地可以自己引水,花费为\(w[i]\),或者连接其他被 ...
- BZOJ3230: 相似子串
3230: 相似子串 Time Limit: 20 Sec Memory Limit: 128 MBSubmit: 913 Solved: 223[Submit][Status]Descripti ...
- voucer
<style type="text/css"> .fieldset_s{border: 1px #dedede solid;padding: 19px; color: ...
- Epub2基础知识介绍
一.什么是epub epub是一个完全开放和免费的电子书标准.它可以“自动重新编排”的内容. Epub文件后缀名:.epub 二. epub组成 Epub内部使用XHTML(或者DTBook)来展现文 ...
- lihgtoj 1006
记忆化搜索下即可. #include<cstdio> #include<string> #include<cstring> #include<iostream ...
- JZ2440开发笔记(7)——2440启动方式
JZ2440的启动方式有两种,一种是从NOR FLASH中启动,还有一种就是从NAND FLASH中启动. 如果从NOR FLASH启动,CPU会访问NOR FLASH的0地址,而0地址位于BANK0 ...
- 【原】Spark中Job如何划分为Stage
版权声明:本文为原创文章,未经允许不得转载. 复习内容: Spark中Job的提交 http://www.cnblogs.com/yourarebest/p/5342404.html 1.Spark中 ...