Angular 2.0.1 AsyncPipe 不适用于 Rx 主题

2024-04-08

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

问题是 NgFor 和 asyncPipe 不能与主题一起使用,这是一个问题吗?

这有效:

成分:

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

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

Template

<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();
  }
}

Template

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

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

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

解决方案,在组件中创建一个可观察变量。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 2.0.1 AsyncPipe 不适用于 Rx 主题 的相关文章

随机推荐