【问题标题】:Firestore get() all documents in a collection returns an errorFirestore get() 集合中的所有文档返回错误
【发布时间】:2018-05-06 07:55:41
【问题描述】:

我正在尝试使用documentation 中定义的 get() 方法迭代集合中的所有文档,但它对我不起作用。我收到get is not a function 错误,我做错了什么?

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

【问题讨论】:

    标签: javascript angular firebase google-cloud-firestore


    【解决方案1】:

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

    收集方法valueChanges返回一个Observable

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

    您可以订阅 valueChanges 返回的 Observable

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

    或者您可以使用CollectionReference 获取Promise

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      • 2018-05-09
      • 2018-12-31
      相关资源
      最近更新 更多