简体   繁体   中英

Angular4 Rxjs Observable Limit Backend HTTP Requests

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).

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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM