Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Subscribe / Unsubscribe Observables in case of http calls

I recently came to know that we must unsubscribe the subscription before Angular destroys the component, and failure to do so could create a memory leak.

I also know that we can get a reference to the subscription and by calling unsubscribe method on that subscription we can subscribe. For example

private sub: any;

ngOnInit() {
  this.sub = this.route.params.subscribe(params => {
     let id = +params['id']; // (+) converts string 'id' to a number
     this.service.getHero(id).then(hero => this.hero = hero);
   });
}


ngOnDestroy() {
  this.sub.unsubscribe();
}

Is this necessary in the case of HTTP calls as well? If yes, then what's the best practice in this case.

For example, we usually have something like this to post some data through HTTP

let body = JSON.stringify({ name });
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });

this.http.post(this.heroesUrl, body, options)
                .map(this.extractData)
                .subscribe((data) => {
                 //do something with data
                })
                .catch(this.handleError);

Will the below work, and is it the best way to unsubscribe in the case of HTTP calls?

private sub: any;

.....
....

this.sub = this.http.post(this.heroesUrl, body, options)
                .map(this.extractData)
                .subscribe((data) => {
                 //do something with data
                 this.sub.unsubscribe();
                })
                .catch(this.handleError);
like image 713
Naveed Ahmed Avatar asked Jun 24 '16 23:06

Naveed Ahmed


People also ask

Do we need to unsubscribe from HTTP calls in Angular?

You don't have to unsubscribe. You should know if there are issues in your logic, that could cause Problems in your subscription.

Do I need to unsubscribe from observable Angular?

No need to unsubscribe from internal observables of an application scoped service since this service never get's destroyed, unless your entire application get's destroyed, there is no real reason to unsubscribe from it and there is no chance of memory leaks.

Do I need to unsubscribe from observable in a service?

As you probably know when you subscribe to an observable or event in JavaScript, you usually need to unsubscribe at a certain point to release memory in the system. Otherwise, you will have a memory leak. A memory leak occurs when a section of memory that is no longer being…

How to unsubscribe from an observable in angular?

To prevent this memory leaks we have to unsubscribe from the subscriptions when we are done with. We do so by calling the unsubscribe method in the Observable. In Angular, we have to unsubscribe from the Observable when the component is being destroyed.

How to end a subscription in angular?

Angular calls the ngOnDestroy method once the component is not used anymore. Therefore, its the perfect place to end our subscriptions. While this solution might be OK for if you have one or two subscriptions, it becomes very tedious if you have more subscriptions.

How do I unsubscribe from observable in Java?

Use the unsubscribe method A Subscription essentially just has an unsubscribe () function to release resources or cancel Observable executions. To prevent this memory leaks we have to unsubscribe from the subscriptions when we are done with. We do so by calling the unsubscribe method in the Observable.

How to unsubscribe from observables in RxJS?

We can gather them subscriptions in an array and unsubscribe from them in the ngOnDestroy: @Component ( {...}) Observables subscribe method returns an object of RxJS’s Subscription type. This Subscription represents a disposable resource.


1 Answers

No, it is not necessary to unsubscribe. In short, NG2 will clean up after itself as seen here:

    if (response.ok) {
      responseObserver.next(response);
      // TODO(gdi2290): defer complete if array buffer until done
      responseObserver.complete();
      return;
    }
    responseObserver.error(response);
  };
like image 129
Cory Forward Avatar answered Oct 19 '22 15:10

Cory Forward