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. 网络编程(一) 利用NSURLSession发送GET POST请求

    Xcode 7.0后,http链接不能直接访问(https可以),需要在Info.plist增加下面一项才能正确访问. 使用NSURLSession进行网络请求的流程: 1.构造NSURL 2.构造N ...

  2. 【HDOJ】1225 Football Score

    这种结构体排序的题,十分容易考上机题,qsort+结构体解决.马上就要机考了,多练习一下这样的题目也好. #include <stdio.h> #include <string.h& ...

  3. hadoop2.2编程:从default mapreduce program 来理解mapreduce

    下面写一个default mapreduce 的程序: import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapr ...

  4. Bootstrap中的less基础

    在线编译 因为 less 的语法毕竟相对简单,所以一些在线工具可以很轻松的做到.比如 http://less.cnodejs.net http://www.ostools.net/less  一般都有 ...

  5. android ListView上拉加载更多 下拉刷新功能实现(采用pull-to-refresh)

    Android实现上拉加载更多功能以及下拉刷新功能, 采用了目前比较火的PullToRefresh,他是目前实现比较好的下拉刷新的类库. 目前他支持的控件有:ListView, ExpandableL ...

  6. [liu yanling]测试方法

    1.定义 是把所有可能的输入数据,即程序的输入域划分成若干部分(子集),然后从每一个子集中选取少数具有代表性的数据作为测试用例.该方法是一种重要的,常用的黑盒测试用例设计方法. 2.划分等价类 等价类 ...

  7. while MyJob = '程序员' do --- 序

    因为自己的际遇,忽然想写点什么留在这个世上.也许只是想证明自己活过吧. 所以,这不会是一个过去时的小说,这将是一个接近进行时的记叙.之所以是接近,因为我只有在空余时间,才能记录最近的经历.出于保护隐私 ...

  8. mysql 资料总结 长期更新

    http://blog.csdn.net/ww1982_0_0_0/article/details/9169613  引入employess

  9. Java笔记(二十二)……Collection集合

    概述 为什么会出现集合类 面向对象语言对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,就对对象进行存储,集合就是存储对象最常用的一种方式 数组和集合类同是容器,有何不同 数组虽然也可以存储 ...

  10. Codevs 1222 信与信封问题 二分图匹配,匈牙利算法

    题目: http://codevs.cn/problem/1222/ 1222 信与信封问题   时间限制: 1 s   空间限制: 128000 KB   题目等级 : 钻石 Diamond 题解 ...