我通過服務公開HTTP GET請求,並且有幾個組件正在使用此數據(用戶的配置文件詳細信息)。我希望第一個組件請求能夠實際向服務器執行HTTP GET請求並緩存結果,以便隨後的請求將使用緩存的數據,而不是再次調用服務器。使用angular2 http服務緩存結果
這是一個服務的例子,你會如何推薦使用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;
}
});
}
}
另一個有趣的解決方案,我認爲你正在尋找[分享](https://github.com/Reactive-Extensions/RxJS/blob/master /doc/api/core/operators/share.md)。我有一個[plnkr](http://plnkr.co/edit/hM4TSt4hlx4DA4xe37WU?p=preview),所以你可以看到它的工作。請注意,這不是緩存,但它可能適用於你:)(運行一次,看到網絡選項卡,然後從'http.get'中移除'.share()'並查看其差異)。 –
我試過你的方法,但是當從兩個不同的組件調用getUserProfile(帶.share())時,GET請求仍然會在服務器上執行兩次。雖然ProfileService是使用@Inject(ProfileService)profileService在調用組件的兩個構造函數中注入的。我在這裏錯過了什麼? – Sagi
,這取決於。如果你在每個組件中注入服務,你會得到兩個不同的實例(通過注入我的意思是使用'providers/viewProviers')。如果是這種情況,應該只在頂層組件中注入它(在這兩者之間)。如果情況並非如此,如果可能的話,你應該添加更多的代碼和repro。 –