Angular 5
The issue I am having is that when I navigate away from a component, the component is still listening and acting upon service subscription updates.
My Service
export class GlobalVarsService {
private selectedDepartment = new BehaviorSubject<number>(null);
selectedDepartment$ = this.selectedDepartment.asObservable();
...
}
MyComponent
ngOnInit() {
this.globalVarsService.selectedDepartment$.subscribe( selectDepartment => {
this.refreshReportData();
});
}
I could be 3 clicks away from MyComponent
but if I update selectedDepartment
then the subscription will still fire and this.refreshReportData
will execute. Obviously I do not want this because it's extra HTTP calls that are completely unnecessary.
I have tried implementing onDestroy
to validate that the component destruction is happening when I navigate way and it does. So from my perspective it appears that my destroyed component is still active and listening for subscription events. There also is no unsubscribe
method available on this.globalVarsService.selectedDepartment$
so I can't put that into my onDestroy
method either.
What do I do?
yes, you have to unsubscribe inside ngOnDestroy, but if you use Async Pipe, it will handle that automatically
import { Subscription } from "rxjs/Subscription";
private subscription: Subscription ;
ngOnInit() {
this.subscription = this.globalVarsService.selectedDepartment$.subscribe( selectDepartment => {
this.refreshReportData();
});
}
ngOnDestroy() {
this.subscription.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