In my Angular2 set up I've got a component that calls a service method. The service method returns an Observable and the component subscribes to it.
As I want the service to cache recent calls, I'd intercept the the data in the Observable with the map
function. The exemplary service method looks like this
provideData():Observable<Data> {
return this.http.get(url).
map(resp => resp.json()).
map(data => {
this.cachedData = _.cloneDeep(data);
return data;
}
}
This approach works for me, however, I'm unsure if I don't abuse the map
function which doesn't map anything. It's just an interceptor to lay hold of the data. Are there better or more recommended ways?
PS.: This is not necessarily about caching, rather than the appropriate usage of the map
function for non-mapping operations. In this question Günter's widely approved answer does actually the same thing and uses map
for that. On the other hand, the user olsn stated in the comments that do
would be even more appropriate.