Angularfire: Allow Firestore collection and doc to accept a Reference as input

Created on 12 Nov 2017  路  3Comments  路  Source: angular/angularfire

angularfire2/database allows initialising a object/list using either a path string or a reference. It would be nice to allow the same for the firestore.

The new interface would look something like this:

collection<T>(pathOrRef: string | firebase.firestore.CollectionReference, queryFn?: QueryFn): AngularFirestoreCollection<T>
doc<T>(pathOrRef: string | firebase.firestore.DocumentReference): AngularFirestoreDocument<T>

It should be a simple change, I can make a PR for it if it sounds interesting.

Most helpful comment

We are actually using something very similar in our app already. Inspired by this post I created a service to wrap and extend angularfire with this functionality. It looks like this:

// types

type CollectionPredicate<T> = string | AngularFirestoreCollection<T>;
type DocPredicate<T> = string | AngularFirestoreDocument<T>;

// return a reference

col<T>(ref: CollectionPredicate<T>, queryFn?): AngularFirestoreCollection<T> {
    return typeof ref === 'string' ? this.afs.collection<T>(ref, queryFn) : ref;
}

doc<T>(ref: DocPredicate<T>): AngularFirestoreDocument<T> {
    return typeof ref === 'string' ? this.afs.doc<T>(ref) : ref;
}

// return an observable

doc$<T>(ref: DocPredicate<T>): Observable<T> {
    return this.doc(ref).snapshotChanges().map(doc => {
        return doc.payload.data() as T;
    });
}

col$<T>(ref: CollectionPredicate<T>, queryFn?): Observable<T[]> {
    return this.col(ref, queryFn).snapshotChanges().map(docs => {
        return docs.map(a => a.payload.doc.data()) as T[];
    });
}

All 3 comments

We are actually using something very similar in our app already. Inspired by this post I created a service to wrap and extend angularfire with this functionality. It looks like this:

// types

type CollectionPredicate<T> = string | AngularFirestoreCollection<T>;
type DocPredicate<T> = string | AngularFirestoreDocument<T>;

// return a reference

col<T>(ref: CollectionPredicate<T>, queryFn?): AngularFirestoreCollection<T> {
    return typeof ref === 'string' ? this.afs.collection<T>(ref, queryFn) : ref;
}

doc<T>(ref: DocPredicate<T>): AngularFirestoreDocument<T> {
    return typeof ref === 'string' ? this.afs.doc<T>(ref) : ref;
}

// return an observable

doc$<T>(ref: DocPredicate<T>): Observable<T> {
    return this.doc(ref).snapshotChanges().map(doc => {
        return doc.payload.data() as T;
    });
}

col$<T>(ref: CollectionPredicate<T>, queryFn?): Observable<T[]> {
    return this.col(ref, queryFn).snapshotChanges().map(docs => {
        return docs.map(a => a.payload.doc.data()) as T[];
    });
}

I am interested in this as well.

Just opened a PR #1487

Was this page helpful?
0 / 5 - 0 ratings