简体   繁体   English

Angular4 Rxjs可观察的限制后端HTTP请求

[英]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. 我试图限制应用程序中不必要的HTTP调用的数量,但是每次我订阅Observable时,都会向服务器发出请求。 Is there a way to subscribe to an observable without firing http request? 有没有一种方法可以订阅可观察对象而不触发http请求? 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. 不知道我是否正确理解了您的问题,但似乎您想在服务中缓存第一个HTTP请求的结果,因此,如果第一个组件获取数据,第二个组件(另一个订户)将检索缓存的数据。 If that's the case, declare a service provider on the module level so Angular creates a singleton object. 如果是这种情况,请在模块级别声明一个服务提供者,以便Angular创建一个单例对象。 Then inside the service create a var that stores the data after the first retrieval. 然后在服务内部创建一个var,用于在第一次检索后存储数据。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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