通过使用Http,我们调用一个执行网络调用并返回http observable的方法:
getCustomer() { return this.http.get('/someUrl').map(res => res.json()); }
let network$ = getCustomer(); let subscriber1 = network$.subscribe(...); let subscriber2 = network$.subscribe(...);
我们要做的是确保这不会导致多个网络请求。
这可能看起来像一个不寻常的情况,但其实是很常见的:例如,如果调用者订阅了observable显示一个错误消息,并将其传递给模板使用async管道,我们已经有两个订阅者。
在RxJs 5中正确的做法是什么?
也就是说,这似乎工作正常:
getCustomer() { return this.http.get('/someUrl').map(res => res.json()).share(); }
但是这是在RxJs 5中这样做的惯用方法,还是我们应该做别的事情呢?
缓存数据,如果可用缓存,返回否则做出HTTP请求。
import {Injectable} from '@angular/core'; import {Http,Headers} from '@angular/http'; import {Observable} from 'rxjs/Observable'; import 'rxjs/observable/of'; import 'rxjs/add/operator/share'; import 'rxjs/add/operator/map'; import {Data} from './data'; @Injectable() export class DataService { private url:string = 'https://cors-test.appspot.com/test'; private data: Data; private observable: Observable<any>; constructor(private http:Http) {} getData() { if(this.data) { // if `data` is available just return it as `Observable` return Observable.of(this.data); } else if(this.observable) { // if `this.observable` is set then the request is in progress // return the `Observable` for the ongoing request return this.observable; } else { // example header (not necessary) let headers = new Headers(); headers.append('Content-Type','application/json'); // create the request,store the `Observable` for subsequent subscribers this.observable = this.http.get(this.url,{ headers: headers }) .map(response => { // when the cached data is available we don't need the `Observable` reference anymore this.observable = null; if(response.status == 400) { return "FAILURE"; } else if(response.status == 200) { this.data = new Data(response.json()); return this.data; } // make it shared so more than one subscriber can get the result }) .share(); return this.observable; } } }
另请参见缓存HTTP响应以获得更多RXjsy方法