我有一个角度应用程序,我正在读取一个文件并对其进行处理,这个处理是可观察的一部分。我有一个服务,它返回可观察的一个(ng忙碌:订阅)。我在我的组件中订阅了这个可观察的。可观察的被分配给一个显示微调器的ngBusy。现在微调器即使在订阅完成后也会继续旋转。我知道我们需要取消订阅可观察的。但是当我在我们订阅的同一个方法中取消subscri时,我甚至看不到微调器显示。我们应该总是使用ngOn销毁来取消订阅吗?
service. ts
const obsrv:Observable
obsrv= new Observable((observer) => {
// observable execution
observer.next(this.items)
observer.complete()
})
组件. 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();
}
这是一个很好的方法,可以使用带直到和取消订阅
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();
}