Angular 2 + rxjs:带有.share()运算符的异步管道 [英] Angular 2 + rxjs: async pipe with .share() operator

查看:75
本文介绍了Angular 2 + rxjs:带有.share()运算符的异步管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用.share()运算符的可观察对象上使用异步管道时(由于后端中的计算昂贵),我偶然发现了这种行为:

When using the async pipe on a observable that is using the .share() operator (due to expensive calculations in the backend), I stumbled upon this behaviour:

data$ = (new Observable(observer => {
    let counter=0;
    observer.next(counter)

    window.setInterval(() => {
      observer.next(counter);
      counter++;
    }, 2000);
  }))
  .share();

模板:

{{ (data$|async) !== null }}
{{ (data$|async) !== null }}

初始值的输出是:

true false

以下输出(超过2秒)是:

The following outputs (after more than 2 seconds) are:

true true

这也是我期望的第一个值的行为. 如果我忽略了.share(),那么第一个值的输出将是"true true",正如我所期望的那样.我想上面的行为是由于模板中的第一个表达式触发了可观察的执行,并且一旦第二个异步管道订阅了可观察的,数据就已经消失了.这个解释正确吗?而我该如何避免这种行为呢?

which is the behavior I would expect for the first value, too. If I omit the .share(), the output for the first value is "true true", as I would expect. I suppose the behavior above is due to the fact that the first expression in the template triggers observable execution, and once the second async pipe subscribes to the observable, the data is already gone. Is this explanation correct? And how can I avoid this behavior?

推荐答案

根据参考

异步管道订阅了一个Observable或Promise,并返回它发出的最新值.

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted.

在RxJS 4中,shareReplay用于实现所需的行为.

In RxJS 4, shareReplay is used to achieve the desired behaviour.

在RxJS 5中,与shareReplay直接对应的是publishReplay,后跟refCount(请参阅说明讨论).

In RxJS 5, a direct counterpart to shareReplay is publishReplay followed by refCount (see the explanation and the discussion).

应该是

data$ = (new Observable(observer => { ... }))
.publishReplay(1)
.refCount();

这篇关于Angular 2 + rxjs:带有.share()运算符的异步管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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