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. UVA 11294 Wedding

    给n对夫妇安排座位,其中0h,0w分别表示新郎,新娘.同一对新郎,新娘不能坐在同一侧,而且互为通奸关系的人不能同时坐在新娘对面. 这道题目真是掉尽节操啊,,,欧美的氛围还是比较开放的. 分析: 首先说 ...

  2. Android ListView(Selector 颜色)

    listview_color.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout ...

  3. easyui源码翻译1.32--EasyLoader(简单加载)

    前言 扩展自$.fn.datebox.defaults,使用$.fn.datetimebox.defaults重写默认值对象.下载该插件翻译源码 源码 /** * jQuery EasyUI 1.3. ...

  4. ArcGIS Engine生成等值线(C#)

    原文:ArcGIS Engine生成等值线(C#) 本文介绍c#写的利用ArcGIS Engine生成等值线的方法.c#写的根据雨量站的降雨量值内插出降雨量等值线的功能.做几点说明:根据离散点生成等值 ...

  5. 点点滴滴-NET下的常用框架

    刘冬的博客:http://www.cnblogs.com/GoodHelper/category/214139.html (Spring.net和Nhibernate) Kyo-yo  : http: ...

  6. Django中的Model继承

    Django 中的 model 继承和 Python 中的类继承非常相似,只不过你要选择具体的实现方式:让父 model 拥有独立的数据库:还是让父 model 只包含基本的公共信息,而这些信息只能由 ...

  7. linux多线程驱动中调用udelay()对整个系统造成的影响(by liukun321咕唧咕唧)

    以前没考虑过这个问题,而且之前可能运气比较好,虽然用了udelay但也没出什么奇怪的问题,今天在 CSDN上看到了一篇关于此问题帖子,觉得很受用,再此做简要的记录和分析: 驱动开的是内核线程 跟普通进 ...

  8. 手势识别官方教程(4)在挑划或拖动手势后view的滚动用ScrollView和 HorizontalScrollView,自定义用Scroller或OverScroller

    简单滚动用ScrollView和 HorizontalScrollView就够.自定义view时可能要自定义滚动效果,可以使用 Scroller或 OverScroller Animating a S ...

  9. 安装Sublime Text 3插件

    按 Ctrl+` 或者如下图调出Console 粘贴以下代码到底部命令行并回车: import urllib.request,os; pf = 'Package Control.sublime-pac ...

  10. 修改tomcat的部署名称

    找到指定工程下面的.setting目录下面的org.eclipse.wst.common.component文件,可以看到以下的配置 <?xml version="1.0" ...