问题
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>
回答1:
As Frank van Puffelen commented, your best bet to access a user's subcollection is
this.db.collection(`users/${userId}/saved`)
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.
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.
来源:https://stackoverflow.com/questions/58546545/return-a-sub-collection-in-firebase-using-angular-firestore