I have an endpoint that retrieves all the comments for a post and in that list there's the user_id
property for each comment so from that I make another call that retrieves the user information such as name or email. This is what I've implemented using forkJoin and flatMap.
getCommentsList() {
return this.http.get("COMMENTS_ENDPOINT")
.map(res => res.json())
.flatMap(comments => Observable.forkJoin(comments.map(comment => this.getUserDetail(comment.user_id)
.map(user => (comment.user = user, comment))))));
}
getUserDetail(id) {
return this.http.get("USER_ENDPOINT/id")
.map(res => res.json());
}
Although this works fine, duplicate calls to user endpoint get made when there's the same user commenting more than once. How can I store the user data and use it when the same user data is to be retrived? I have tried
storedUsers:any = {};
getUserDetail(id) {
if (this.storedUsers[id]) {
console.log("using cache");
return Observable.of(this.storedUsers[id]);
}
return this.http.get("USER_ENDPOINT/id")
.map(res => res.json())
.do(user => this.storedUsers[user.id] = user);
}
But never in console it logs using cache.