我想知道我是否多次使用Observable.subscribe()。
在我的组件类中,我有一个函数loadData()。它调用另一个函数this.service.getData(),该函数使用HttpClient.get()对服务器执行HTTP请求。
当前,在我的函数loadData()中,我订阅了this.service.getData()的结果。
每次用户单击“更新”按钮时,我都想调用我的函数loadData()。
private loadData() {
this.loading = true;
const subscription = this.service.getData()
.pipe(
// console.log() with a delay added for test - START
map(val => {
window.setTimeout(() => {
// This will print true.
console.log('After delay: Is Subscriber closed?', subscription.closed);
}, 10);
return val;
}),
// console.log() with a delay added for test - END
takeUntil(this.ngUnsubscribe))
.subscribe(data => {
this.data = data;
// This will print false.
console.log('Is Subscriber closed?', subscription.closed);
},
error => {
console.error(error);
throw error;
},
() => {
this.loading = false;
});
}
getData(): Observable<DataObject> {
const uri = encodeURI(this.configService.getUri());
const headers = new HttpHeaders();
if (this.pipelineEtag) {
headers.set('If-None-Match', this.pipelineEtag);
}
return this.http.get(uri, {
headers: headers,
observe: 'response'
}).pipe(
map(resp => this.processResponse(resp)),
catchError(error => this.handleError(error, this.envProduction))
);
}
每次HTTP调用返回值时,Observable都会完成。因此在服务中执行这样的操作是安全的
loadData() {
return this.http.get<Data>(dataUrl).pipe(
// tap(data => console.log(data)), // eyeball results in the console
catchError(err => this.handleError(err))
);
}
然后打电话
this.service.loadData().subscribe((data:Data) => do somthing)
您甚至可以调用exhaustMap或switchMap来控制Observable流,以免“提示”服务器太多时间
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句