Issue
I'd like to list of the collection of Firestore database inside Ionic4 app so I use the doc in the section listCollection so I applied the example code in my code :
this.afs.firestore.listCollections().then(collections => {
for (let collection of collections) {
console.log(`Found collection with id: ${collection.id}`);
}
});
here is my constructor :
constructor(private router: Router,
private afs: AngularFirestore,
private fireauth: AngularFireAuth) { }
And I get this error : error TS2339: Property 'listCollections' does not exist on type 'Firestore'.
I can not use the property listCollections whereas it is in the online doc...
Solution
Actually, as detailed in the Firestore JS SDK documentation, retrieving a list of collections IS NOT possible with the mobile/web client libraries.
This is true for the roots collections of your Firestore database but also for the sub-collections of a Firestore document.
However, as you have mentioned in your question, it IS possible with the Cloud Firestore Node.js Client API. Therefore you can use a Cloud Function to list the collections of your Firestore DB and call this Cloud Function from your front-end.
Since you will call this Cloud Function from your app we use a Callable Cloud Function.
Cloud Function Code
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.getCollections = functions.https.onCall(async (data, context) => {
const collections = await admin.firestore().listCollections();
const collectionIds = collections.map(col => col.id);
return { collections: collectionIds };
});
Front-end Code
To call this callable Cloud Function from your Angular app, just follow the Angularfire documentation for Cloud Functions.
import { Component } from '@angular/core';
import { AngularFireFunctions } from '@angular/fire/functions';
@Component({
selector: 'app-root',
template: `{ data$ | async }`
})
export class AppComponent {
constructor(private fns: AngularFireFunctions) {
const callable = fns.httpsCallable('getCollections');
this.data$ = callable({ .... });
}
}
Note that this approach is inspired from the following article, which describes how to list all subcollections of a Cloud Firestore document with the JS SDK. (Disclaimer: I'm the author)
Answered By - Renaud Tarnec
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.