5

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);
KB_
  • 2,113
  • 2
  • 26
  • 28
Naveed Ahmed
  • 10,048
  • 12
  • 46
  • 85

1 Answers1

5

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);
  };
Cory Forward
  • 116
  • 3
  • Not only does cleanup happen automatically here, but it will happen anytime an `Observable` completes. `http` requests always complete because they emit only 1 value by their very nature so we do not need to clean them up - the `Observable` chain will clean itself up. See my answer here http://stackoverflow.com/a/41177163/939634 – seangwright Dec 16 '16 at 04:17
  • 3
    What happens if the http call was made but has not returned yet and the user leaves the view? I think in that case you will be left with a dangling subscription? – Thibs Apr 04 '17 at 00:25