如何正确地将 Observable 转换为数组

How to properly convert Observable into Array

我目前正在尝试将 Observable 转换为数组,以便我可以使用 ngFor 在 HTML 中迭代数组。

这是我当前的 Typescript 代码。当我控制台记录 testArray 数组时,它说它是未定义的。

item$: Observable<any[]>;
testArray: Array<any[]>;

  constructor(
    private afs: AngularFirestore,
    private route: ActivatedRoute,
  ) {
      this.item$ = afs.collection('testsTaken', ref => ref.where('testCreator', '==', this.id).where('testTitle', '==', this.testTitle)).valueChanges();
      this.item$.subscribe(x => this.testArray = x);
      console.log(this.testArray); // yields undefined
 
  }

Observable 是异步工作的。 Javascript 不会在订阅之外等待它的结果,并且你的 console.log() 在 Observable 中的代码被处理之前很久就被触发了。看看这个:

this.item$.subscribe(x => {
       this.testArray = x;
       console.log(this.testArray);
});

console.log() 正在打印未定义,因为您的订阅在 console.log 打印后发出,因此数组仍未定义。 您可以检查它并进行如下更改:

 this.item$.subscribe(x => {
   this.testArray = x;
   console.log(this.testArray);
 });

如果你想 运行 在 *ngFor 上使用数组你有 2 个选项:

选项 1:

this.item$.subscribe(x => this.testArray = x);

您可以在您的模板中使用它,例如(示例):

<div class="test" *ngFor="let item of testArray"> {{item}} </div>

选项 2:

异步管道(您可以在此处阅读更多相关信息:https://angular.io/api/common/AsyncPipe) 简而言之,这与在组件类型脚本中订阅一样,但在模板中(使用它有很多 好处)。

示例代码:

<div class="test" *ngFor="let item of item$ | async">{{item}} </div>;