我通过服务公开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;
}
});
}
}
Run Code Online (Sandbox Code Playgroud)