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.

3
  • 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, 2020 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, 2020 at 17:08
  • 3
    Does this answer your question? Is it necessary to unsubscribe from observables created by Http methods? Dec 22, 2020 at 17:31

2 Answers 2

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

2
  • 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 7, 2021 at 9:36
  • it is the same thing eventually you are making an http request and subscribing to it
    – jagjeet
    Jan 8, 2021 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();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.