mwo
mwo

Reputation: 85

Firestore get() all documents in a collection returns an error

I'm trying to iterate all the documents in the collection with the get() method as defined in the documentation, however it doesn't work for me. I get a get is not a function error, what am I doing wrong?

export class MainComponent implements OnInit {
    selectedCharacter: number = null;
    people: Observable<any>;
    private peopleCollection: AngularFirestoreCollection<Character>;

    constructor(private db: AngularFirestore,
          private route: ActivatedRoute,
          private location: Location) {
      this.peopleCollection = db.collection('people');
      this.people = this.peopleCollection.valueChanges();

      this.route.params.subscribe(
          params => (this.selectedCharacter = +params['id'])
      );
    }

    ngOnInit() {
        this.peopleCollection.get().then(function(querySnapshot) {
            querySnapshot.forEach(function(doc) {
                console.log(doc.id, " => ", doc.data());
            });
        });
   }
}

Upvotes: 1

Views: 5440

Answers (1)

ibenjelloun
ibenjelloun

Reputation: 7733

TL;DR : this.peopleCollection.ref.get()

The collection method valueChanges returns an Observable :

export declare class AngularFirestoreCollection<T> {
    ...
    valueChanges(events?: DocumentChangeType[]): Observable<T[]>;
    ...
}

You could subscrible to the Observable returned by valueChanges :

ngOnInit() {
    this.people.subscribe(data => console.log(data));
}

Or you can use the CollectionReference to get the Promise:

ngOnInit() {
    this.peopleCollection.ref.get().then(data => console.log(data));
}

Upvotes: 5

Related Questions