博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Angular 2] Handle Reactive Async opreations in Service
阅读量:6958 次
发布时间:2019-06-27

本文共 3196 字,大约阅读时间需要 10 分钟。

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
>; constructor(private http: Http, private store: Store
) { 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
>; constructor(private http: Http, private store: Store
) { 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
) { this.items = itemsService.items; itemsService.loadItems(); }

We base on async pipe to update the dom:

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.

转载地址:http://lvmil.baihongyu.com/

你可能感兴趣的文章
GPS定位系统源码GPS定位系统 GPSBD专为二次开发而设计 ...
查看>>
LocalDateTime API 整理
查看>>
ASK动画获三千资本A+轮投资,将加速推进原创动漫作品的创作 ...
查看>>
Postgresql服务器配置-设置参数
查看>>
你想了解Python中的 == 和IS 其他?
查看>>
最强求职攻略:java程序员如何通过阿里、百度社招面试
查看>>
B2B电商营销若有十分惊艳,九分在内容营销
查看>>
阿里云护航罗振宇2018“时间的朋友”跨年演讲,与千万观众一起跨年
查看>>
如何使用Hanlp加载大字典
查看>>
jdbc练习题
查看>>
CRM工具简介
查看>>
配置管理 ACM 在高可用服务 AHAS 流控降级组件中的应用场景
查看>>
生于疼痛的阿里云
查看>>
别再逼三星了,它在起死回生的路上挣扎很久了
查看>>
sql server 高可用故障转移(6)
查看>>
elasticsearch插件二—— kibana插件安装详解(Elasticsearch教程09)|MVP讲堂
查看>>
Kubernetes 1.8.x 全手动安装教程
查看>>
Python.Unix和Linux系统管理指南
查看>>
在K8S上使用RancherVM,以容器的方式跑虚机
查看>>
Unity3dC#位运算讲解与示例
查看>>