I expose an HTTP GET request through a service, and several components are using this data (profile details on a user). I would like the first component request to actually perform the HTTP GET request to the server and cache the results so the the consequent requests will use the cached data, instead of calling the server again.
Here's an example to the service, how would you recommend implementing this cache layer with Angular2 and 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;
}
});
}
}
.share()from thehttp.getand see the difference).providers/viewProviers). If that's the case you should inject it only in your top level component (between those two). If that's not the case you should add more code and a repro if possible.share()it will return a different share everytime (that kind of makes sense, didn't see it at first). But if you refactor it to make the request in the constructor and assigning it to a variable it will work. TL;DR plnkr with the example working : plnkr.co/edit/kvha8GH0b9qkw98xLZO5?p=preview