I have a shared service (starting from this suggestion) that cache and returns some data after first http request:
export class SharedService {
constructor(private http:Http) {
}
getData() {
if (this.cachedData) {
return Observable.of(this.cachedData);
} else {
return this.http.get(...)
.map(res => res.json())
.do((data) => {
this.cachedData = data;
});
}
}
}
My problem is that I have some directives and components inside the same template that are all initialized at the same time and each one call simultaneously (inside ngInit function) the getData method (all of them before the first one succeeded) and so the service starts many http requests instead of returning cached data. Can someone suggest me how to avoid this side effect?