我有一个角度应用程序,我正在读取文件并处理它,这个处理是可观察的一部分。我有一个返回可观察的服务(ngbusy:订阅)。我在我的组件中订阅了这个observable。将observable分配给显示微调器的ngBusy。现在,即使订阅完成,微调器也会继续旋转。我知道我们需要取消订阅obervable。但是当我在我们订阅的相同方法中取消订阅时,我甚至看不到显示微调器。我们是否应该始终使用ngOndestroy取消订阅。
service.ts
const obsrv:Observable
obsrv= new Observable((observer) => {
// observable execution
observer.next(this.items)
observer.complete()
})
component.ts
processItems() {
ngbusy = this.myservice.observable.subscribe(items => {
//perform some business logic
});
this.myservice.observable.unsubscribe(); //not working here
}
您必须取消订阅订阅,而不是取消订阅:
processItems() {
const ngbusy = this.myservice.observable.subscribe(items => {
// perform some business logic
// unsubscribe at some point...
ngbusy.unsubscribe();
});
// this will unsubscribe immediately...
ngbusy.unsubscribe();
}
这是使用takeuntil和ngUnsubscribe的好方法
private ngUnsubscribe: Subject = new Subject();
ngOnInit() {
this.myThingService.getThings()
.takeUntil(this.ngUnsubscribe)
.subscribe(things => console.log(things));
/* if using lettable operators in rxjs ^5.5.0
this.myThingService.getThings()
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe(things => console.log(things));
*/
this.myThingService.getOtherThings()
.takeUntil(this.ngUnsubscribe)
.subscribe(things => console.log(things));
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}