要遍历子集合和文档使用 angularfirestore ,可以按照以下步骤进行操作:
npm install firebase @angular/fire
import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule } from '@angular/fire/firestore';
// ...
@NgModule({
imports: [
AngularFireModule.initializeApp(environment.firebase),
AngularFirestoreModule,
// ...
],
// ...
})
export class AppModule { }
FirestoreService
),用于获取和处理 Firestore 数据:import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class FirestoreService {
private collection: AngularFirestoreCollection;
constructor(private firestore: AngularFirestore) {
this.collection = this.firestore.collection('your_collection_name');
}
getSubcollection(parentId: string, subcollectionName: string): Observable {
return this.collection.doc(parentId).collection(subcollectionName).valueChanges();
}
getDocument(parentId: string, documentId: string): Observable {
return this.collection.doc(parentId).collection('your_subcollection_name').doc(documentId).valueChanges();
}
}
FirestoreService
:import { Component, OnInit } from '@angular/core';
import { FirestoreService } from './firestore.service';
import { Observable } from 'rxjs';
@Component({
selector: 'app-your-component',
template: `
Subcollections:
- {{ subcollection.name }}
Documents:
- {{ document.name }}
`
})
export class YourComponent implements OnInit {
subcollections$: Observable;
documents$: Observable;
constructor(private firestoreService: FirestoreService) { }
ngOnInit() {
const parentId = 'your_parent_id';
const subcollectionName = 'your_subcollection_name';
const documentId = 'your_document_id';
this.subcollections$ = this.firestoreService.getSubcollection(parentId, subcollectionName);
this.documents$ = this.firestoreService.getDocument(parentId, documentId);
}
}
在上面的代码示例中,你需要替换以下值:
your_collection_name
:你的 Firestore 集合名称your_subcollection_name
:你的子集合名称your_parent_id
:父级文档的 IDyour_document_id
:要获取的文档的 ID这样,你就可以遍历子集合和文档了。记得在 Firebase 控制台中正确配置你的 Firestore 规则以允许读取数据。
上一篇:遍历字节字符串的n位块
下一篇:遍历子进程并逐行根据字段进行过滤