以下是一个完整的示例代码,展示了如何将集合项推入数组中:
import { Component } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
@Component({
selector: 'app-root',
template: `
Collection Items:
- {{ item.name }}
`
})
export class AppComponent {
items: any[] = [];
constructor(private firestore: AngularFirestore) {
this.getCollectionItems();
}
getCollectionItems() {
this.firestore.collection('collectionName').valueChanges().subscribe((items: any[]) => {
this.items = items;
});
}
}
在这个例子中,我们创建了一个AppComponent,它在构造函数中调用getCollectionItems()方法来获取集合项并将其推入items数组中。在模板中,我们使用ngFor指令来遍历items数组并显示每个集合项的name属性。
请注意,你需要在app.module.ts中正确配置AngularFire模块和Firestore的引导信息。