0

There is a lot of questions and comments on this topic but I have a more specific question and it may seem stupid to ask but id like to be sure.

I've read that you do not need to unsubscribe from HttpClient calls in angular as it will automatically do this.

But if I had a separate service that had this function:

SERVICE

get() {
    return this.httpClient.get('someurlhere');
}

And then had a component consume it like this:

COMPONENT

this.service.get().subscribe(() => {});

Would I then need to unsubscribe as the subscription is now in the component?

Keen to know if this makes any difference at all.

Useme Alehosaini
  • 2,998
  • 6
  • 18
  • 26
DBoi
  • 627
  • 2
  • 17
  • 35
  • If the caller does not know, it wouldn't hurt to unsubscribe. However, I always make sure that methods return cold observables like the http client does, and I use fields for hot observables. Hot observables need to be unsubscribed. – Silvermind Dec 22 '20 at 16:57
  • So am I right in thinking its a 'no' you don't have to, even though the subscription is in the component? Also what do you mean by 'fields'? – DBoi Dec 22 '20 at 17:08
  • 3
    Does this answer your question? [Is it necessary to unsubscribe from observables created by Http methods?](https://stackoverflow.com/questions/35042929/is-it-necessary-to-unsubscribe-from-observables-created-by-http-methods) – R. Richards Dec 22 '20 at 17:31

2 Answers2

4

you should unsubscribe

there is no problem regarding memory leak as http observables are completed after first response.

but your logic in subscribe block can cause problem, for example if your api call is taking too long and user decides to leave the page then in that case since you have not unsubscribed the observable your logic such as login or navigation inside subscribe can cause problems

and just to inform you this question has been already answered here

Is it necessary to unsubscribe from observables created by Http methods?

you can refer to this link for detailed answers

jagjeet
  • 585
  • 2
  • 10
  • Thanks for answering the question. I did see that link but wondered if because I had my get request in one file and then the subscribe in another file, it made any difference whatsoever in regards to unsubscribing etc. It seems its better to unsubscribe either way so I'll continue to do that - thanks again. – DBoi Jan 07 '21 at 09:36
  • it is the same thing eventually you are making an http request and subscribing to it – jagjeet Jan 08 '21 at 17:33
2

Yes. This is how you do it: you create a variable :

private _subscription = new Subscription();

In your code:

this._subscription.add(this.service.get().subscribe(() => {}););

ngOnDestroy():

this._subscription.unsubscribe();
Olaru Alina
  • 458
  • 4
  • 8