什么是分享RxJs 5的角2 HTTP网络调用的结果的正确方法是什么? [英] What is the correct way to share the result of an Angular 2 Http network call in RxJs 5?

查看:148
本文介绍了什么是分享RxJs 5的角2 HTTP网络调用的结果的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过使用HTTP,我们称之为做了网络调用和返回观察到的HTTP方法:

  getCustomer(){
    返回this.http.get('/ someUrl')的地图。(RES => res.json());
}

如果我们借此观察到的,多个用户添加到它:

 让网络$ = getCustomer();让Subscriber1的网络= $ .subscribe(...);
让subscriber2用户=网络$ .subscribe(...);

我们要做的,是确保这不会导致多个网络请求。

这似乎是一个不寻常的场景,但它实际上是相当常见的:例如,如果呼叫者订阅可观察到显示错误信息,并使用异步管道把它传递给模板,我们已经有两个用户<。 / p>

什么是做在RxJs 5的正确方法?

也就是说,这似乎很好地工作:

  getCustomer(){
    返回this.http.get('/ someUrl')的地图。(RES =&GT; res.json())份额();
}

但是,这是在RxJs 5这样做的惯用方式,还是应该做别的事情呢?


解决方案

根据@Cristian建议,这$ P $被多次发出pvents网络电话:

  getCustomer(){
    返回this.http.get('/ someUrl')
        .MAP(RES =&GT; res.json())publishLast()引用计数()。
}

共享,如果返回被传递到例如在 CONCAT 运营商,这也有效。

根据需要取消或重试,分享可能是一个更好的选择,看评论波纹管。

By using Http, we call a method that does a network call and returns an http observable:

getCustomer() {
    return this.http.get('/someUrl').map(res => res.json());
}

If we take this observable and add multiple subscribers to it:

let network$ = getCustomer();

let subscriber1 = network$.subscribe(...);
let subscriber2 = network$.subscribe(...);

What we want to do, is ensure that this does not cause multiple network requests.

This might seem like an unusual scenario, but its actually quite common: for example if the caller subscribes to the observable to display an error message, and passes it to the template using the async pipe, we already have two subscribers.

What is the correct way of doing that in RxJs 5?

Namely, this seems to work fine:

getCustomer() {
    return this.http.get('/someUrl').map(res => res.json()).share();
}

But is this the idiomatic way of doing this in RxJs 5, or should we do something else instead?

解决方案

As per @Cristian suggestion, this prevents the network calls from being issued multiple times:

getCustomer() {
    return this.http.get('/someUrl')
        .map(res => res.json()).publishLast().refCount();
}

Unlike share, this also works if the return is passed to for example to the concat operator.

Depending on the need of cancelation or retry, share might be a better option, see comments bellow.

这篇关于什么是分享RxJs 5的角2 HTTP网络调用的结果的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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