[英]How to subscribe to an ongoing http request
I need to request some data from the server only once, then use it as long as the app is loaded 我只需要从服务器请求一些数据,然后只要加载了应用程序就可以使用它
getData(callback: Function) {
if (this.data) {
callback(this.data);
} else {
this.query.http.get('url', res => {
this.data = res;
callback(this.data);
});
}
}
the problem is that when the app starts a lot of components request the data at once, resulting in 30-40 http request, so I came up with this solution: 问题是,当应用程序启动时,许多组件立即请求数据,导致30-40 http请求,因此我想出了以下解决方案:
getData(callback: Function) {
if (this.data) {
callback(this.data);
} else if(!this.gettingData) {
this.gettingData = true;
this.query.http.get('url', res => {
this.data = res;
callback(this.data);
});
} else {
setTimeout(() => {
getData(callback);
}, 500)
}
}
so it requests the data again after 500ms if the http request is in progress, if the request returns an error I reset the gettingdata to false, it works, but it feels dirty and wrong, how can I subscribe to the ongoing http request called by another function invoker? 因此,如果http请求正在进行,它将在500毫秒后再次请求数据,如果请求返回错误,我将Gettingdata重置为false,它可以正常工作,但是感觉很脏和有错误,我该如何订阅由调用的正在进行的http请求另一个函数调用器?
how about this? 这个怎么样?
getData () {
this.query.http.get('url'). subscribe(
res=> this.data = res,
err=> console.log(err));
}
then just use this.data throughout your component, you could emit the data if it's from a child component like so 然后只要在整个组件中使用this.data,就可以从子组件中发出数据,就像这样
@Output() valueChange = new EventEmitter();
private data;
getData () {
this.query.http.get('url'). subscribe(
res=> {
this.data = res;
this.valueChange.emit(this.data);
},
err=> console.log(err));
}
i hope this helps. 我希望这有帮助。 or somewhat answers your question 或有点回答你的问题
introduce a service which manages your http requests. 引入一项管理您的http请求的服务。 A service is basically a singleton which can be used via dependency injection. 服务基本上是一个单例,可以通过依赖注入来使用。 Create it with 用它创建
ng -generate service myservice
and inject it by declaring a field of type myservice
as a constructor argument of your component. 并通过声明类型为myservice
的字段作为组件的构造函数参数来注入它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.