Search code examples
angulartypescriptrxjsobservableangular-httpclient

what happens if we does not subscribe to HttpClient request which return observables in angular


I am new to Angular & typescript , trying to understand HttpClient, observables & subscribe

When i do this in a function of a component

console.log(this.http.get('assets/user.json'));

I am receiving an object but can not see any request going to https://localhost:4200/assets/user.json in debugger network while if i change code to

this.http.get('assets/userDetail.json').subscribe(data => this.user = { name:  data['name']});

I can see the network request hitting the required URL. why this is happening ? my understanding was this.http.get('assets/userDetail.json') will hit the url even if we does not subscribe to response data stream.


Solution

  • To understand the matter it's good to know there are hot & cold observables - the cold need to be subscribed otherwise they're not fired, the hot are fired no matter if something is subscribed to them.

    Angular's HttpClient returns a cold Observable, so it's not fired until subscribed. To be sure if an observable is hot or cold you need to check corresponding docs, see for example HttpClient.post:

    Constructs an Observable which, when subscribed, will cause the configured POST request to be executed on the server.

    An example of an Angular's hot observable is e.g. ActivatedRoute.params - how to use - you see there is no subscription.

    The fact an observable is hot/cold has more consequences than just having or not having to subscribe:

    • when subscribing, you should also unsubscribe in some cases to avoid memory leaks plus there is Angular's async pipe, which manages subscription for you; there is an article on the matter: Don't forget to unsubscribe (Angular specific)

    • there is a perfect article by Ben Lesh on the subject from a general point of view: Hot vs Cold Observables (not specific to Angular).