I am trying to clean-up a project of mine with a bunch of duplicated code, I call my back-end a bunch of times from multiple components which really slows down my program.
Previously each component, inside the ngOnInit() method, had something like this in it in order to initialize an array of services:
this.http.get(this.ds.services_URL).map((res)=>res.json()).subscribe(
(data) =>{
this.Services=data;
});
What I wanted to do though is having one service that makes the http call once and then my components can request my service for the data.
I've tried having something like this in my Service:
private loadServices()
{
this.http.get(this.services_URL).map((res)=>res.json()).subscribe(
(data) =>{
this.serviceO=new Observable(observer=>{
setTimeout(()=>{
observer.next(data);
observer.complete();
},1000);
});
});
}
serviceO being an Observable, the different components would subscribe to it rather than the http.get result.
The problem here being (besides the fact that I am not sure of how to actually set an Observable's value), that we are actually redefining the entire Observable asynchronously, so it is actually impossible for the Observer to have a reference to the observable (I get "Cannot read property 'subscribe' of undefined" kind of exception)
Seeing the problem I am facing, I think I am not going the right direction, so does anyone know a better direction on how to achieve what I want to achieve?
return this.http.get(this.services_URL).map(res => res.json());
? – JB Nizet