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

我怕爱的太早我们不能终老 提交于 2019-11-28 17:11:13

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.

Think map as a middleware which transforms the response.

this.http.get('http://172.17.40.41:8089/api/Master/GetAllCountry')
.map(r=>r.json())
 .subscribe(result => {
              // here result would have json object that was parsed by map handler...
            },failurCallback,completeCallback)

subscribe is used to invoke the observable, please read a good doc on cold-vs-hot-observables

You need subscribe to run your async request. If you just set map - no requests will trigger. You can check.

Good practice to use map to preproccess you data because many subscribers can comsume your results. So instead of adding preprocessing to each client (subscriber) you can prepare single output with single data schema for all.

N4R35H

.map() is an rxjs operator, it will show the result in array [] form either .json() form

https://www.learnrxjs.io/operators/transformation/map.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!