[英]how to wait for http request for returning response with in subscribe method in angular 8?
[英]How to subscribe to an ongoing http request
我只需要从服务器请求一些数据,然后只要加载了应用程序就可以使用它
getData(callback: Function) {
if (this.data) {
callback(this.data);
} else {
this.query.http.get('url', res => {
this.data = res;
callback(this.data);
});
}
}
问题是,当应用程序启动时,许多组件立即请求数据,导致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)
}
}
因此,如果http请求正在进行,它将在500毫秒后再次请求数据,如果请求返回错误,我将Gettingdata重置为false,它可以正常工作,但是感觉很脏和有错误,我该如何订阅由调用的正在进行的http请求另一个函数调用器?
这个怎么样?
getData () {
this.query.http.get('url'). subscribe(
res=> this.data = res,
err=> console.log(err));
}
然后只要在整个组件中使用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));
}
我希望这有帮助。 或有点回答你的问题
引入一项管理您的http请求的服务。 服务基本上是一个单例,可以通过依赖注入来使用。 用它创建
ng -generate service myservice
并通过声明类型为myservice
的字段作为组件的构造函数参数来注入它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.