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的更多相关文章

  1. [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 ...

  2. angular ajax的使用及controller与service分层

    一个简单的例子,控制层:.controller('publishController',['$scope','publishService', function($scope,publishServi ...

  3. ionic准备之angular基础———服务provider 和 factory和service(9)

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. [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 ...

  5. [Angular] Wrap a third party lib into service

  6. Angular service, 服务

      早上开车上班, 发现车快没油了, 于是拐进加油站. 有一辆出租车也在加油..   Angular service在一个应用里是以单例形式存在的. 这个单例的实例是由service factory( ...

  7. angular 服务 service factory provider constant value

    angular服务 服务是对公共代码的抽象,由于依赖注入的要求,服务都是单例的,这样我们才能到处注入它们,而不用去管理它们的生命周期. angular的服务有以下几种类型: 常量(Constant): ...

  8. [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 ...

  9. [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 ...

随机推荐

  1. [状压dp]经典TSP

    0出发 每个顶点经过一次 回到0 最小花费. O($n^2 \times 2^n$) 记忆化搜索: // s: 已经访问过的节点状态 v: 出发位置 int dfs(int s, int v) { ) ...

  2. UVA 125 Numbering Paths

    题目大意:给定n条单向边,求图中任意两点的连通路径的数目.其中点是从0-输入中出现的最大的点. 可以用floyd-warshall算法或者dfs. for(int k = 0; k < n; k ...

  3. Windows 内核(WRK)编译

    引子 WRK 是微软于 2006 年针对教育和学术界开放的 Windows 内核的部分源码, WRK(Windows Research Kernel)也就是 Windows 研究内核, 在 WRK 中 ...

  4. S3C2410 实验三——跑马灯实验

    http://www.evernote.com/shard/s307/sh/f2a748e7-34c4-4ce6-acac-82a756cc9e82/ad5813188d655e504857970db ...

  5. android 颜色收集及部分gridview样式设置

    < ?xml version="1.0" encoding="utf-8" ?> < resources> < color nam ...

  6. Nginx+Keepalived 做负载均衡器

    1.安装 keepalived   1 2 3 4 5 6 7 8 9 tar zxvf keepalived-XXXX.tar.gz ./configure --prefix=/usr/local/ ...

  7. VJ1061迎春舞会之三人组舞

    题目链接 推了半个下午..写的三重超时了  加了点单调队列的思想 优化了下过了 dp[i][j] 第二组的最右边的人选第J个人 那最左边肯定选第j-1个人 肯定是选相邻的 dp[i][j] = min ...

  8. URI Scheme

    1. 什么是URI Scheme? 一般情况下,遇到这种概念不清的问题,最好的第一手资料就是wiki,实在看不懂,再看百度百科,但前者给出的资料一般都是更加准确一些. 以下为维基百科和百度百科关于这个 ...

  9. bzoj1196

    带有限制的生成树 首先不难想到二分答案转化为判定性问题 假设二分出了一个答案p, 首先我们先考虑建一级公路. 由于一级公路费用是大于二级公路的,所以对于那些一级公路花费<=p的道路, 不难想到让 ...

  10. ☀【JS】检测属性

    <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8& ...