如何取消订阅观察

时间:2018-04-27 23:52:42

标签: angular observable unsubscribe

我有一个角度应用程序,我正在读取文件并对其进行处理,此处理是可观察的一部分。 我有一个返回可观察的服务(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
}

2 个答案:

答案 0 :(得分:0)

您必须取消订阅订阅,而不是取消订阅:

processItems() {
    const ngbusy = this.myservice.observable.subscribe(items => {
        // perform some business logic 


        // unsubscribe at some point...
        ngbusy.unsubscribe();
    });

    // this will unsubscribe immediately...
    ngbusy.unsubscribe();

}

答案 1 :(得分:0)

这是使用 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();
}
相关问题