使用Angular Firestore在Firebase中返回子集合 [英] Return a sub-collection in firebase using Angular firestore
问题描述
我有一个子集合,称为子集合,它以嵌套集合的形式保存到每个用户.用户有其自己的字段和一个保存的集合,其中包含两个字段和一个数组.我只能显示用户字段,但是我不知道访问每个用户子集合的正确方法.
I have a sub-collection called saved as a nested collection to each user. User has its own fields and a collection of saved which contains two fields and an array. I can display only user fields but i don't know a proper way to access each user sub-collection.
export class SavedComponent implements OnInit{
public saved: Saved[];
public currentUser: any = null;
public user: User;
private subscriptions: Subscription[] = [];
constructor(
// Adding saved service
private savedService: SavedService,
private auth: AuthService,
private loadingService: LoadingService,
private route: ActivatedRoute,
private db: AngularFirestore
) {
// this.loadingService.isLoading.next(true);
}
this.subscriptions.push(
this.auth.currentUser.subscribe( user => {
this.currentUser = user;
this.loadingService.isLoading.next(false);
// Console log the current authentiucated user
console.log(this.currentUser);
})
);
this.subscriptions.push(
this.route.paramMap.subscribe( params => {
const userId = params.get('userId');
const userRef: AngularFirestoreDocument<User> = this.db.doc(`users/${userId}`);
userRef.valueChanges().subscribe(user => this.user = user);
})
)
// Example of html template
<div class="row justify-content-center">
<div class="col-xs-12 col-sm-8 col-md-6 text-center name">
{{user?.firstName}} {{user?.lastName}}
</div>
</div>
推荐答案
正如Frank van Puffelen所说,访问用户子集合的最佳选择是
As Frank van Puffelen commented, your best bet to access a user's subcollection is
this.db.collection(`users/${userId}/saved`)
要访问保存的子集合,您需要首先访问用户集合中的用户文档.根据此 Firestore文档,该查询的结构用于访问子集合的文档,您可以在访问集合,然后访问文档等之间交替选择,以到达子集合或子集合的文档.
To reach your saved subcollection, you need to first access your user document inside your users collection. As per this Firestore document, a query's structure to access a subcollection's document, you alternate between accessing a collection, then a document, and so on to reach a subcollection, or a subcollection's document.
您不能引用集合中的集合或文档中的文档.
You cannot reference a collection in a collection or a document in a document.
为集合或子集合指定this.db.collection,为集合或子集合的文档指定this.db.doc非常重要.
It is important that you specify this.db.collection for a collection or subcollection, and this.db.doc for a collection's or subcollection's documents.
这篇关于使用Angular Firestore在Firebase中返回子集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!