Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Components still listening to subscriptions after being destroyed [duplicate]

Tags:

angular

rxjs

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?

like image 882
Raymond Holguin Avatar asked May 07 '18 18:05

Raymond Holguin


1 Answers

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();
}
like image 144
Fateh Mohamed Avatar answered Oct 02 '22 11:10

Fateh Mohamed