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

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

问题描述

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 Subject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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