Warm tip: This article is reproduced from serverfault.com, please click

Do I need to unsubscribe from httpClient with subscription in component

发布于 2020-12-22 16:52:44

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.

Questioner
DBoi
Viewed
0
jagjeet 2020-12-23 01:41:31

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