I've been attempting to implement a new rxjs Observable
in an Angular 2 component using TypeScript. I have created a service, MyService
that returns an observable in one of its methods, e.g.,
export class MyService {
getMyObs(){
return new Observable(observer => {
observer.next(42);
});
}
}
Then in my Angular 2 component I subscribe to this observable in OnInit, e.g.,
export class MyComponent implements OnInit {
obs: any;
constructor(private myService: MyService){};
ngOnInit {
this.obs = myService.getMyObs().subscribe(data => {
// Do stuff here...
});
}
}
The RxJs documentation talks about unsubscribing from your observable such that your observable knows to no longer emit messages to your observer. Therefore, I figured I should be unsubscribing from the observable when my component gets destroyed, something like
export class MyComponent implements OnInit, OnDestroy {
obs: any;
constructor(private myService: MyService){};
ngOnInit {
this.obs = myService.getMyObs().subscribe(data => {
// Do stuff here...
});
}
ngOnDestroy {
this.obs.unsubscribe();
}
}
Whilst this makes sense to me, the typescript compiler throws (and indeed the application throws) saying there is no unsubscribe
method. There appears to be no such method described in the type definition files. How do I correctly unsubscribe from an observable using TypeScript?
You need add unsubscribe method to your Observable
., Disposing Observable Executions
return new Observable(observer => {
observer.next(42);
return () => {
console.log('unsubscribe')
}
});
First create Subscription as follow.
private obs: Subscription = new Subscription();
Then assign to observable.
this.obs = myService.getMyObs().subscribe(data => {
if(data !== null){
this.obs.unsubscribe()
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With