我想知道我是否使用了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流,以免“提示”太多时间服务器
这是正确的用法,创建多个订阅者没有风险。
从文档:
AsyncPipe会自动为您订阅(和取消订阅)。
技术细节是,一旦Http请求完成,就会调用observable的.complete
方法,该方法会杀死所有当前用户。这意味着您的订户已创建,使用,并立即被丢弃。
所以最后