Angular 2.0.1 AsyncPipe不适用于Rx主题 [英] Angular 2.0.1 AsyncPipe doesn't work with Rx Subject

查看:71
本文介绍了Angular 2.0.1 AsyncPipe不适用于Rx主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AsyncPipe与BehaviorSubject一起使用,但是我不想用空数据初始化我的服务,因此,我使用Subject intead.

AsyncPipe works with BehaviorSubject, but I don't want to initialize my service with empty data, for this reason I use Subject intead.

问题是NgFor,而asyncPipe不适用于Subject,这是一个问题吗?

The problem is NgFor and asyncPipe doesn't work with Subject, is it an issue?

这有效:

组件:

export class AppComponent {
  foo = new BehaviorSubject<Array<number>>([1,2,3]);

  getFoo(){
     return this.foo.asObservable();
  }
}

模板

<span *ngFor="let e of foo.asObservable() | async">{{e}}</span>

这无效:

组件

export class AppComponent {
  foo = new Subject<Array<number>>();

  constructor(){
     setTimeout(() => {
          this.foo.next([1,2,3]);
     }, 3000);
  }

  getFoo(){
     return this.foo.asObservable();
  }
}

模板

<span *ngFor="let e of foo.getFoo() | async">{{e}}</span>

推荐答案

这里的问题是从我的模板中调用一个方法-这意味着每次运行更改检测时,我都会调用您的getFoo()函数,该函数将返回一个新的可观察对象的实例,它将重置异步管道.

The problem here is calling a method from my template - this means every time change detection runs, I'm calling your getFoo() function, which returns a new instance of the observable, which resets the async pipe.

因此,无论您在NgFor中调用getFoo(),代码都将失败.

So, the code fails whether you call getFoo() in the NgFor.

Solucion,在组件中创建一个可观察的变量.

Solucion, create an observable variable in the component.

这篇关于Angular 2.0.1 AsyncPipe不适用于Rx主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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