Angular HttpClient unsubscribe

Viewed 8885

Is there a need to unsubscribe from the Observable the Angular HttpClient's methods return?

For example:

this.http.get(url).subscribe(x => this.doSomething());

Do I need to unsubscribe from this subscription? I am asking this is because I don't know if Angular handles it itself. Plus the request is one-off not continuously. I tend to think I don't need to. What are your thoughts?

As per the below post: Angular/RxJs When should I unsubscribe from `Subscription`

RxJS handles the one-off subscription but I didn't find anything in their doc.

4 Answers

You can unsubscribe from all Observables in your page at the 'same' time when your leave the page with ngOnDestroy. You pipe an Observable which is activated when you leave the page and closes the function.

export class X implements OnInit, OnDestroy {
  private unsubscribe$ = new Subject();

  ngOnInit() {
    this.functionOne();
  }

  ngOnDestroy() {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }

  functionOne() {
    this.service
      .getData()
      .pipe(takeUntil(this.unsubscribe$))
      .subscribe(
        (result) => {},
        (error) => {}
      );    
  }
}

There are 2 ways to handle this:

1) Yes, you have to unsubscribe manually if you are subscribing to observable normally in the ts file. usually we can do unsubscribe in the ngOnDestroy() life cycle method

2) If you use async pipe syntax on the observable in angular template, then it automatically close the subscription

observable | async 

Refer below: https://angular.io/api/common/AsyncPipe

Yes, it is necessary to unsubscribe it according to https://blog.angularindepth.com/the-best-way-to-unsubscribe-rxjs-observable-in-the-angular-applications-d8f9aa42f6a0

Here is what I do:


export class CustomerSummaryComponent implements OnInit, OnDestroy {
  subscriptions: Subscription[];

  ngOnInit() {
    this.subscriptions = [];

    this.subscriptions.push(
        this.customerService.getCustomer(this.customerId).subscribe(
        data => {
        },
        error => {
            console.log(error);
        }
        )
    );
  }

  ngOnDestroy() {
    for (const x of this.subscriptions) {
      x.unsubscribe();
    }
  }
}

Related