本文介绍了如何退订可观察的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个角度应用程序,在这里我正在读取文件并对其进行处理,这种处理是可观察到的.我有一项服务,该服务返回可观察到的(ngbusy:subscription).我在我的组件中订阅了这个可观察的内容.可观察对象已分配给显示微调器的ngBusy.现在,即使订阅已完成,微调器仍会继续旋转.我知道我们需要退订可观的东西.但是,当我按照订阅的相同方法退订时,我什至看不到微调器显示.我们是否应该始终使用ngOndestroy退订.

I have an angular application where I am reading a file and processing it and this processing is part of observable. I have a service which returns the observable an (ngbusy:subscription). I am subscribing to this observable in my component. The observable is assigned to an ngBusy which displays a spinner.Now the spinner keeps spinning even after subscribe is complete. I know we need to unsubscribe to the obervable.But when I unsubscri in the same method where we are subscribing, I don't even see the spinner displayed.Should we always use ngOndestroy to unsubscribe.

service.ts

service.ts

const obsrv:Observable
obsrv= new Observable((observer) => {    
    // observable execution
    observer.next(this.items)
    observer.complete()
})

component.ts

component.ts

processItems() {
    ngbusy  = this.myservice.observable.subscribe(items => {
        //perform some business logic 
    });
    this.myservice.observable.unsubscribe(); //not working here
}

推荐答案

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

这篇关于如何退订可观察的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 19:10