如何正确地将Observable转换为Array



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

这是我当前的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

}

我尝试了这个帖子的建议,但我仍然无法让它发挥作用

console.log((打印未定义,因为您的订阅在console.log打印后发出,所以数组仍然未定义。你可以检查它并做出这样的改变:

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

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

选项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)简而言之,这与组件类型脚本中的subscribe相同,但在模板中(使用它有很多优点(。

示例代码:

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

一个Observable异步工作。Javascript不会在订阅之外等待其结果,并且在处理Observable内部的代码之前很久就已经触发了console.log((。看看这个:

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

最新更新