[Angular 2] Handle Reactive Async opreations in Service
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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2015-06-24 [Javascript + rxjs] Introducing the Observable
2015-06-24 [Javascript] IIFE