5

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?

Raymond Holguin
  • 1,050
  • 2
  • 12
  • 35
  • https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription – martin May 07 '18 at 18:35

1 Answers1

7

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();
}
Fateh Mohamed
  • 20,445
  • 5
  • 43
  • 52
  • I read somehwere on stackoverflow that the recommended way of handling subscriptions in a component is with the takeUntil operator. I find that way also more elegant than tracking each subscription. See this answer: https://stackoverflow.com/questions/42490265/rxjs-takeuntil-angular-components-ngondestroy?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – tom van green May 08 '18 at 14:49