【问题标题】:Angular 2 AsynPipe isn't working with an ObservableAngular 2 AsynPipe 不适用于 Observable
【发布时间】:2016-09-13 22:16:20
【问题描述】:

我收到以下错误:

EXCEPTION: Cannot find a differ supporting object '[object Object]' in [files | async in Images@1:9]

这是模板的相关部分:

<img *ngFor="#file of files | async" [src]="file.path">

这是我的代码:

export class Images {
  public files: any; 
  public currentPage: number = 0;
  private _rawFiles: any;

  constructor(public imagesData: ImagesData) {
    this.imagesData = imagesData;  
    this._rawFiles = this.imagesData.getData()
        .flatMap(data => Rx.Observable.fromArray(data.files));
    this.nextPage();
  }

  nextPage() {
    let imagesPerPage = 10;
    this.currentPage += 1;
    this.files = this._rawFiles
                    .skip((this.currentPage - 1) * imagesPerPage)
                    .take(imagesPerPage);
    console.log("this.files:", this.files);                
  }
}

末尾的console.log 表明它是一个可观察对象:

this.imagesData.getData() 从 Angular 的 Http 服务返回一个可观察到的常规 RxJS,那么为什么异步管道不能使用它呢?也许我使用flatMap() 的方式是错误的,它搞砸了?

如果我尝试像这样订阅这个 observable:

this.files = this._rawFiles
                .skip((this.currentPage - 1) * imagesPerPage)
                .take(imagesPerPage)
                .subscribe(file => {
                  console.log("file:", file);
                });

它按预期打印对象列表:

【问题讨论】:

  • *ngFor 只迭代一个数组,而不是一系列事件,因此您的 Observable 需要返回一个数组而不是一系列对象。
  • 我会选择使用 scan 运算符的 Observable&lt;File[]&gt;

标签: javascript angular reactive-programming rxjs observable


【解决方案1】:

改用Observable&lt;File[]&gt;

this.files = this._rawFiles
         .skip((this.currentPage - 1) * imagesPerPage)
         .take(imagesPerPage)
         .map(file => [file])
         .startWith([])
         .scan((acc,value) => acc.concat(value))

这应该不需要手动代码到subscribe,并且应该与您当前的模板完美配合。

我在this blog post.做了非常相似的事情

【讨论】:

  • 谢谢。它有效,虽然它并不完全漂亮。我已经从服务器接收了一个数组,并且只将它转换为一个流,以便能够使用 RxJS 的实用方法(skiptake)。如果我每次都必须像这样转换为数组,那么完全不使用 RxJS 进行数组操作会更容易
猜你喜欢
  • 2019-09-22
  • 2019-02-07
  • 2016-09-15
  • 2018-02-14
  • 2019-04-30
  • 1970-01-01
  • 2017-11-10
  • 2018-02-10
  • 1970-01-01
相关资源
最近更新 更多