Angularfire: Query collection in firestore just once

Created on 9 Jan 2018  路  4Comments  路  Source: angular/angularfire

If i want to get the full contents of a collection just one time how do I go about doing so. I can't seem to find this in issues, or in the documentation.

Thank you

Most helpful comment

Hi @ericcancil! We do not natively support the .get() method, but you do have two options.

Use the underlying reference

constructor(afs: AngularFirestore) {
  afs.collection('items').ref.get();
}

Use .take(1)

// import { take } from 'rxjs/operators';
constructor(afs: AngularFirestore) {
  afs.collection('items').valueChanges().pipe(take(1));
}

All 4 comments

The guides on the actual firebase site has this example

db.collection("cities").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        console.log(doc.id, " => ", doc.data());
    });
});

I'm guessing this is from a different version because it no longer exists.

Hi @ericcancil! We do not natively support the .get() method, but you do have two options.

Use the underlying reference

constructor(afs: AngularFirestore) {
  afs.collection('items').ref.get();
}

Use .take(1)

// import { take } from 'rxjs/operators';
constructor(afs: AngularFirestore) {
  afs.collection('items').valueChanges().pipe(take(1));
}

Just an update for people searching. the get() is supported now. (I think :P)

```javascript
db.collection('items')
.get()
.pipe(
map((res: QuerySnapshot) => res.docs.map(d => d.data()),
take(1)
)

@davideast - Is there anything in AngularFire that replicates @ericcancil native firestore code example yet?

Also, just to confirm, that example, if put into an angular service for example would only query the database once no matter how many times you navigate to that component? I think with the AngularFire collection query using snapshot changes, (and async in the HTML) it queried the DB every time I navigated to the component...I _think_.

Is ericcancil's example the best way to avoid querying a collection every time you navigate to a component that has that service referenced?

Was this page helpful?
0 / 5 - 0 ratings