0
votes

I am trying to limit the number of unnecessary HTTP calls in my application but everytime I subscribe to an Observable there is a request being made to the server. Is there a way to subscribe to an observable without firing http request? My observable in service looks like that:

getServices(): Observable<Service[]> {
    return this.http.get(this.serviceUrl).map(res => res.json())._catch(err => err);
}

Then in my component I subscribe to that observable like this:

this.serviceService.getServices().subscribe(services => this.services = services);

What I would like to achieve is to store data somehow on the service itself (so that I can use that data throughout the whole application without making requests on every component separately, but I would also like to know when that data is received by components (which I usually do by subscription).

1
... Just don't call the function that triggers the request? <.< Why would you subscribe to it if you don't want it to run? Doesn't make any sense. - Chrillewoodz
I subscribe to it because I want the same data that it provides... for now I created a workaround and put "this.services" inside of a subject and created an observable out of the sbuject. - Daniel Kenzo

1 Answers

0
votes

Not sure if I understand your question correctly, but it seems that you want to cache the results of the first HTTP request in the service, so if the first component fetch the data, the second one (another subscriber) would retrieve the cached data. If that's the case, declare a service provider on the module level so Angular creates a singleton object. Then inside the service create a var that stores the data after the first retrieval.

@Injectable()
export class DataService{

    mydata: Array<string>[];

    constructor(private http:Http){}

    getServices(): Observable<string[]> {
        if (this.mydata){
            return Observable.from(this.mydata);  // return from cache
        } else
        {
            return return this.http.get(this.serviceUrl).map(res => res.json())._catch(err => err);
        }
    }
}