如果我手动添加collectionRef,我就可以访问子集合。我尝试在构造函数之外使用 CollectionReference,但收到错误消息,指出类型“UnitlogService”上不存在属性“collectionRef”。我看到的唯一方法是如何在构造函数之前使用 getTasks 或在构造函数之外使用 CollectionReference 。有关子集合的任何帮助或 AngularFire 参考文档都会非常有帮助。
服务文件ts
import { collection, CollectionReference, Firestore }from'@angular/fire/firestore';
export class UnitlogService {
private collectionRef: CollectionReference;
constructor( private firestore: Firestore, private auth: Auth, private storage: Storage ) {
// const id inserted manually
// would like to use id form getTasks(id) which connects the page with this service
const id = 'LvuYX0jreCB1sL5IORCM'
this.collectionRef = collection(this.firestore, `tasks/${id}/unit-logs-sub-collection`);
onAuthStateChanged(this.auth, (user) => {
if (user) {
const tasksQuery = query( this.collectionRef);
const collectionSub = collectionData(tasksQuery, {
idField: 'id',
}) as Observable<Task[]>;
this.tasksSub = collectionSub.subscribe((tasks) => {
this.tasks.next(tasks);
});
} else {
this.tasks.next([]);
this.tasks.unsubscribe();
}
});
}
getTasks(id: any) {
console.log("id",id)
return this.tasks.asObservable()
}
如果您是 AngularFire 用户,则构造函数实际上无法修改。作为解决方法,我跳过了 CollectionReference 并在构造函数之外使用以下代码来查询子集合并将其作为 Observable 返回以在其他页面上使用
服务
import { collection, CollectionReference, Firestore }from'@angular/fire/firestore';
getSubCollection(id: any) {
// id of collection "task" is passed form the page using the service
const col = collection(this.firestore, `tasks/${id}/unit-logs-sub-collection`);
// const col is the link to the sub collection
const tasksQuery = query( col );
const collectionSub = collectionData(tasksQuery, { idField: 'id',}) as Observable<Task[]>;
this.tasksSub = collectionSub.subscribe((tasks) => { this.tasks.next(tasks); console.log("this.tasks",this.tasks);});
// this.tasksSub is a BehaviorSubject
return this.tasks.asObservable();
// returns a Observable {source: BehaviorSubject}
}