why should we use subscribe() over map() in Angular?

Lijin Durairaj picture Lijin Durairaj · Feb 20, 2017 · Viewed 79.2k times · Source

I am trying to take advantage of observables in angular2 and got confused on why should i use map() over subscribe(). Suppose i am getting values from a webApi, like this

  this.http.get('http://172.17.40.41:8089/api/Master/GetAllCountry')

Now using subscribe(success, error, complete) I can get all the values on the success callback and I can return the values on the complete callback. If I can do all theses functionalities then what is the need of map()? Does it give any advantage?

In short, why one should write like this:

this.http.get('http://172.17.40.41:8089/api/Master/GetAllCountry')
    .map(r=>{})
    .subscribe(value => {
    }, error => error, () => {
});

when they can simply write this without the map function:

this.http.get('http://172.17.40.41:8089/api/Master/GetAllCountry')
    .subscribe(value => {        
    }, error => error, () => {           
});

Answer

Günter Zöchbauer picture Günter Zöchbauer · Feb 20, 2017

If you want to return an Observable some other code can subscribe to, but you still want to manipulate the data events in the current method, use map.

The actual user of the observable needs to subscribe(), because without subscribe() the observable won't be executed at all. (forEach() or toArray() and probably others work as well to execute the observable instead of subscribe())

subscribe() returns a Subscription that can not be subscribed to, but it can be used to cancel the subscription.

map() returns an Observable which can be subscribed to.