InvalidPipeArgument: '' for pipe 'AsyncPipe'

InvalidPipeArgument: '' for pipe 'AsyncPipe'

  timers: Observable<ITimer>[]=[];

模板是:

<div *ngFor="let item of timers | async">
  {{ item.time }}
  <div (click)="remove(item.index)">Remove</div>
</div>

为什么会出现此错误?

如果不初始化 this.timers 则异步工作。否则我无法用这种方法获得长度:

 add() {
    let options = {
      finishDate: null,
      time: null,
      index: this.timers.length
    };

    this.timers.push(this.create(options));

  }

行内:index: this.timers.length

来自 Angular async 管道上的文档:

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

但是从你的属性声明来看,它似乎是一个Array。所以不行。

这里不要初始化timers 属性,把timers的类型改成Observable<ITimer[]>

像这样:

timers: Observable<ITimer[]>;

现在取决于您如何初始化 timers 属性。不管你怎么做,只要确保它是 Observable

更新:

根据您的用例,您可以将其作为 Observable 的数组。这是你已经拥有的东西。

timers: Observable<ITimer>[]=[];

您只是在错误的地方使用了 async 管道。试试这个:

<div *ngFor="let item$ of timers">
  <div *ngIf="(item$ | async) as item">
    {{ item.time }}
    <div (click)="remove(item.index)">Remove</div>
  </div>
</div>

Here's a Working Sample StackBlitz for your ref.

或者

你也可以创建一个 BehaviorSubject>:

timersArray: ITimer[] = [];
timers$: BehaviorSubject<Array<ITimer>> = new BehaviorSubject<Array<ITimer>>(this.timersArray);

然后在添加的时候,可以先更新timersArray,然后调用timers$上的next方法更新BehaviorSubject流:

add() {
  let options = {
    finishDate: null,
    time: new Date(),
    index: this.timers.length
  };
  this.timers.push(this.create(options));
  this.timersArray.push(options);
  this.timers$.next(this.timersArray);
}

然后您可以在模板中使用它:

<div *ngFor="let item of (timers$ | async)">
  {{ item.time }}
  <button (click)="remove(item.index)">Remove</button>
</div>

Here's an Updated StackBlitz for your ref.