问题
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
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
}
回答1:
You must unsubscribe from the subscription, not the observable:
processItems() {
const ngbusy = this.myservice.observable.subscribe(items => {
// perform some business logic
// unsubscribe at some point...
ngbusy.unsubscribe();
});
// this will unsubscribe immediately...
ngbusy.unsubscribe();
}
回答2:
This is a good approach using takeuntil and 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();
}
来源:https://stackoverflow.com/questions/50071562/how-to-unsubscribe-for-an-observable