我通过服务公开HTTP GET请求,并且有几个组件正在使用此数据(用户的配置文件详细信息).我希望第一个组件请求实际执行到服务器的HTTP GET请求并缓存结果,以便后续请求将使用缓存数据,而不是再次调用服务器.
这是服务的一个示例,您如何推荐使用Angular2和typescript实现此缓存层.
import {Inject, Injectable} from 'angular2/core'; import {Http, Headers} from "angular2/http"; import {JsonHeaders} from "./BaseHeaders"; import {ProfileDetails} from "../models/profileDetails"; @Injectable() export class ProfileService{ myProfileDetails: ProfileDetails = null; constructor(private http:Http) { } getUserProfile(userId:number) { return this.http.get('/users/' + userId + '/profile/', { headers: headers }) .map(response => { if(response.status==400) { return "FAILURE"; } else if(response.status == 200) { this.myProfileDetails = new ProfileDetails(response.json()); return this.myProfileDetails; } }); } }
tibbus.. 80
该股份()操作符只在第一次请求,当所有的订阅供应与您共创一个又一个的话,将无法正常工作,就会使另一个请求.(这种情况很常见,因为你总是创建/销毁组件的angular2 SPA)
我使用ReplaySubject来存储http observable 的值.该ReplaySubject观察到可以起到前值到它的用户.
服务:
@Injectable() export class DataService { private dataObs$ = new ReplaySubject(1); constructor(private http: HttpClient) { } getData(forceRefresh?: boolean) { // If the Subject was NOT subscribed before OR if forceRefresh is requested if (!this.dataObs$.observers.length || forceRefresh) { this.http.get('http://jsonplaceholder.typicode.com/posts/2').subscribe( data => this.dataObs$.next(data), error => { this.dataObs$.error(error); // Recreate the Observable as after Error we cannot emit data anymore this.dataObs$ = new ReplaySubject(1); } ); } return this.dataObs$; } }
组件:
@Component({ selector: 'my-app', template: `getData from AppComponent` }) export class AppComponent { constructor(private dataService: DataService) {} getData() { this.dataService.getData().subscribe( requestData => { console.log('ChildComponent', requestData); }, // handle the error, otherwise will break the Observable error => console.log(error) ); } } }
完全正常工作PLUNKER
(观察控制台和网络选项卡)
该股份()操作符只在第一次请求,当所有的订阅供应与您共创一个又一个的话,将无法正常工作,就会使另一个请求.(这种情况很常见,因为你总是创建/销毁组件的angular2 SPA)
我使用ReplaySubject来存储http observable 的值.该ReplaySubject观察到可以起到前值到它的用户.
服务:
@Injectable() export class DataService { private dataObs$ = new ReplaySubject(1); constructor(private http: HttpClient) { } getData(forceRefresh?: boolean) { // If the Subject was NOT subscribed before OR if forceRefresh is requested if (!this.dataObs$.observers.length || forceRefresh) { this.http.get('http://jsonplaceholder.typicode.com/posts/2').subscribe( data => this.dataObs$.next(data), error => { this.dataObs$.error(error); // Recreate the Observable as after Error we cannot emit data anymore this.dataObs$ = new ReplaySubject(1); } ); } return this.dataObs$; } }
组件:
@Component({ selector: 'my-app', template: `getData from AppComponent` }) export class AppComponent { constructor(private dataService: DataService) {} getData() { this.dataService.getData().subscribe( requestData => { console.log('ChildComponent', requestData); }, // handle the error, otherwise will break the Observable error => console.log(error) ); } } }
完全正常工作PLUNKER
(观察控制台和网络选项卡)
我省略了userId
处理.它需要管理一个数组data
和一个数组observable
(每个请求一个userId
).
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;
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;
}
}
}
Plunker的例子
您可以在/sf/ask/17360801/找到另一个有趣的解决方案
关于你的最后评论,这是我能想到的最简单的方法:创建一个具有一个属性的服务,该属性将保存请求.
class Service {
_data;
get data() {
return this._data;
}
set data(value) {
this._data = value;
}
}
就如此容易.plnkr中的其他所有内容都不会受到影响.我删除从服务请求,因为它会自动实例化(我们不这样做new Service...
,我不知道一个简单的方法,通过构造函数的参数).
所以,现在,我们有了服务,我们现在所做的就是在我们的组件中发出请求并将其分配给Service变量 data
class App {
constructor(http: Http, svc: Service) {
// Some dynamic id
let someDynamicId = 2;
// Use the dynamic id in the request
svc.data = http.get('http://someUrl/someId/'+someDynamicId).share();
// Subscribe to the result
svc.data.subscribe((result) => {
/* Do something with the result */
});
}
}
请记住,我们的Service实例对于每个组件都是相同的,因此当我们为其分配值时data
,它将反映在每个组件中.
这是带有工作示例的plnkr.
参考
RxJS共享运营商