为什么我们应该在Angular中的map()上使用subscribe()? [英] why should we use subscribe() over map() in Angular?

查看:262
本文介绍了为什么我们应该在Angular中的map()上使用subscribe()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图利用angular2中的可观察对象,对为什么我应该在subscribe()上使用map()感到困惑. 假设我正在像这样从webApi获取值

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')

现在使用subscribe(success, error, complete)可以获取成功回调中的所有值,并且可以返回完整回调中的值.如果我可以完成所有这些功能,那么map()的需求是什么?有什么好处吗?

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?

简而言之,为什么要这样写:

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

他们可以简单地编写而没有地图功能的情况:

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

推荐答案

如果要返回Observable某些其他代码可以预订,但是您仍想在当前方法中操纵数据事件,请使用.

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.

可观察对象的实际用户需要subscribe(),因为如果没有subscribe(),将根本不会执行可观察对象. (forEach()toArray()以及可能其他人也可以执行可观察对象而不是subscribe())

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()返回一个不能订阅的Subscription,但可用于取消订阅.

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

map()返回一个可以订阅的Observable.

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

这篇关于为什么我们应该在Angular中的map()上使用subscribe()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆