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

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

问题描述

我试图利用 angular2 中的 observables 并且对为什么我应该使用 map() 而不是 subscribe() 感到困惑.假设我从 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, () => {
});

当他们可以在没有 map 函数的情况下简单地编写此代码时:

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

推荐答案

如果你想返回一个 Observable 其他一些代码可以订阅,但你仍然想操作当前的数据事件方法,使用map.

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.

observable 的实际用户需要 subscribe(),因为没有 subscribe() observable 根本不会被执行.(forEach()toArray() 和可能其他人也可以执行 observable 而不是 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 中使用 subscribe() 而不是 map() ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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