最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Firestore get() all documents in a collection returns an error - Stack Overflow

programmeradmin1浏览0评论

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());
            });
        });
   }
}

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());
            });
        });
   }
}
Share Improve this question edited Jul 9, 2019 at 4:35 Arnaud 7,45910 gold badges52 silver badges72 bronze badges asked May 6, 2018 at 7:55 mwomwo 851 silver badge7 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

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));
}
发布评论

评论列表(0)

  1. 暂无评论