Reputation: 247
I'm trying to add caching to an Angular2 HTTP service and just can't seem to figure it out.
I followed other posts and have it working perfectly for HTTP services that don't take any parameters e.g.
workSummaries = this.http.get('http://locahost:8080/teams')
.map((response: Response) => response.json())
.publishReplay(1, 3000)
.refCount()
.take(1);
However I'm lost in trying to figure out can I make above work when I introduce a teamId parameter that should be sent with the request.
So ideally if the same teamId has been used in the last X seconds just read from the cache else if it's a new teamId or 3 seconds has past then call the service.
Any help would be great.
Thanks, Kevin.
Upvotes: 8
Views: 1979
Reputation: 21564
You can use a Map to maintain the teamID/team association (I didn't touch the Observable creation part):
summaries = new Map < number, Observable < Team >> ();
getTeam(id: number) {
if (!this.summaries.get(id)) {
let team = this.http.get('http://locahost:8080/teams/' + id)
.map((response: Response) => response.json())
.publishReplay(1, 3000)
.refCount()
.take(1);
this.summaries.set(id, team)
}
return this.summaries.get(id);
}
Upvotes: 10