4

I am trying to unsubscribe from an observable in ngOnDestroy, but it is telling me it does not exist on type Observable.

export class AppComponent implements OnInit {
  public caseData;

  constructor(private _caseService: CaseService,
              private _title: Title,
              private _metaService: Meta) { }

  ngOnInit(): void {
    this._caseService.GetCaseData('en', 'English');
    this._caseService.caseData$.subscribe(res => { this.caseData = res },
      (error) => { console.log(error) });
  }

  ngOnDestroy() {
    this._caseService.caseData$.unsubscribe(); //says it does not exist
  }
}
Adrien Brunelat
  • 4,492
  • 4
  • 29
  • 42
xaisoft
  • 3,343
  • 8
  • 44
  • 72

4 Answers4

13

The subscription itself is returned.

  subscription: Subscription;

  ngOnInit(): void {

    this._caseService.GetCaseData('en', 'English');

    this.subscription = this._caseService.caseData$.subscribe(res => { this.caseData = res },
      (error) => { console.log(error) });

  }
  ngOnDestroy(){
    this.subscription.unsubscribe(); 
  }
Iancovici
  • 5,574
  • 7
  • 39
  • 57
  • Thanks. This worked. If I am using async in other components, I don't need to unsubscribe, correct? – xaisoft Jan 18 '18 at 14:56
  • In general it's better practice to unsubscribe to avoid memory leakage, but that's true for async pipe, it takes care of it for you – Iancovici Jan 18 '18 at 15:42
2

unsubscribe() is a method of a Subscription, not an Observable.

Roland Rácz
  • 2,879
  • 3
  • 18
  • 44
0

That should work:

export class AppComponent implements OnInit {
  public caseData;
  subscription: any;

  constructor(private _caseService: CaseService, private _title: Title, private _metaService: Meta) { }

  ngOnInit() {
    this._caseService.GetCaseData('en', 'English');
    this.subscription = this._caseService.caseData$.subscribe(res => { this.caseData = res },
      (error) => { console.log(error) });
  }

  ngOnDestroy(){
    this.subscription.unsubscribe();
  }
}
Arttu
  • 351
  • 2
  • 14
0

For better way to handle subscription I recommend checking these two links:

https://medium.com/thecodecampus-knowledge/the-easiest-way-to-unsubscribe-from-observables-in-angular-5abde80a5ae3

and

Angular/RxJs When should I unsubscribe from `Subscription`

Nadhir Falta
  • 5,047
  • 2
  • 21
  • 43