[Angular 2] Handle Reactive Async opreations in Service

时间:2023-01-15 13:13:55

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. &lbrack;Angular Testing&rsqb; Unit Testing -- Test component and service&period;

    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. &lbrack;Angular&rsqb; Bind async requests in your Angular template with the async pipe and the &quot&semi;as&quot&semi; keyword

    Angular allows us to conveniently use the async pipe to automatically register to RxJS observables a ...

  5. &lbrack;Angular&rsqb; Wrap a third party lib into service

  6. Angular service&comma; 服务

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

  7. angular 服务 service factory provider constant value

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

  8. &lbrack;Angular Directive&rsqb; 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. &lbrack;Angular Directive&rsqb; 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. session和cookie的辨析&lbrack;阅读&rsqb;

    session和cookie是网站浏览中较为常见的两个概念,也是比较难以辨析的两个概念,但它们在点击流及基于用户浏览行为的网站分析中却相当关键.基于网上一些文章和资料的参阅,及作者个人的应用体会,对这 ...

  2. C&num; string数组转int数组(转载)

    C# string数组转int数组   用法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 //字符串数组(源数组) string[] sNums = new[] {"1 ...

  3. mybatis-高级结果映射之一对多

    目录 1 数据准备 1.2 实体类, 接口和XML 2 一对多映射 2.1 collection集合映射 2.1.1 创建结果实体类 2.1.2 创建结果集 2.1.3 创建对应的方法和XML 2.1 ...

  4. 使用Div &plus; CSS布局页面

    在设计网页时,能够控制好各个模块在页面中的位置是非常关键的.本章将讲解利用Div+CSS对页面元素进行定位的方法. Div是HTML中指定的专门用于布局设计的容器对象 Div是CSS布局的核心对象. ...

  5. 马尔可夫毯(Markov Blanket)

    马尔可夫毯(Markov Blanket) 最近接触到马尔可夫毯(MarkovBlanket)这个概念,发现网上资料不多,通俗易懂的解释甚少,查了一些资料后,决定写一个总结. 提到马尔可夫毯,就会有一 ...

  6. 字幕字体滚动插件——scroxt&period;js

    README scroxt.js Overview scroxt.js是一个字体滚动的插件库,包括视频弹幕滚动,直播弹幕.直播弹幕强制模式.单行水平左右滚动.文本垂直滚动上下,用于简单快捷生成滚动字体 ...

  7. html的body内标签之input系列2

    一,input系列:name属性用于让后台拿数据.value 只是在屏幕上的显示. 1. input type='text' name='query' value="张三"(相当于 ...

  8. key things of ARC

    [key things of ARC] 1.使用原则. 2.__weak变量的使用问题 3.__autoreleasing的使用问题 4.block中易造成的强引用环问题. 5.栈变量被初始化为nil ...

  9. linux中常用命令总结

    一关机/重启/注销 关机 shutdown -h now //立即关机 重启 shutdown -r now //立即重启 reboot 重新启动 注销 logout //退出注销当前用户窗口 exi ...

  10. 《数据结构(C&num;语言描述)》

    本文转载自abatei,数据结构学了很多次,但是只是知道硬性的概念,现在专攻C#语言,对编程语言也有了更深的认识, 买一本C#的数据结构来看看,再一次加深对数据结构的学习,真是一件让人高兴的事. 当当 ...