如何检索单个Firestore文档的ID?

时间:2017-11-10 10:59:31

标签: angularfire2 google-cloud-firestore

这是我的代码:



import { Component, OnInit } from '@angular/core';

import { AngularFirestore
       , AngularFirestoreCollection
       , AngularFirestoreDocument } from 'angularfire2/firestore';

import { Observable } from 'rxjs/Observable';

interface Country {
  id?: string;
  name?: string;
  code?: string;
  flag?: string;
  continent?: string;
}


@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    title = 'Firestore - Documents';

    private countryRef: AngularFirestoreCollection<Country>;
    docId: any;

    constructor( private afs: AngularFirestore ) {

        this.countryRef = this.afs.collection('Country', ref => ref.where('code', '==', 'za'));

        this.docId = this.countryRef.snapshotChanges().map( changes => {
            return changes.map(a => {
                const data = a.payload.doc.data() as Country;
                data.id = a.payload.doc.id;
            return data.id;
            });
        });

    console.log(this.docId);

  }

  ngOnInit() {}

}
&#13;
&#13;
&#13;

我期待一个丑陋的火店id,但我得到了这个:

Observable {_isScalar: false, source: Observable, operator: MapOperator}

1 个答案:

答案 0 :(得分:13)

您正在以Observable const data = a.payload.doc.data() as Country

获取数据

您需要订阅才能获取数据

this.docId.subscribe(docs => {
  docs.forEach(doc => {
    console.log(doc.id);
  })
})

这是推荐的方法

export class AppComponent implements OnInit {
title = 'Firestore - Documents';

private countryRef: AngularFirestoreCollection<Country>;
docId: Observable<Country[]>;

constructor( private afs: AngularFirestore ) {

    this.countryRef = this.afs.collection('Country', ref => ref.where('code', '==', 'za'));

    this.docId = this.countryRef.snapshotChanges().map( changes => {
        return changes.map(a => {
            const data = a.payload.doc.data() as Country;
            const id = a.payload.doc.id;
            return { id, ...data };
        });
    });

this.docId.subscribe(docs => {
  docs.forEach(doc => {
    console.log(doc.id);
  })
})

}

  ngOnInit() {}

}

使用angularfire2从firestore检索数据的最常见做法是.valueChanges().snapshotChanges()。 valueChanges()方法仅提供数据。它会删除所有元数据,包括keys。另一方面.snapshotChanges()将返回包括元数据在内的所有数据。

当您执行const data = a.payload.doc.data() as Country;代码时,它只返回带有out键的数据。当您将其映射到const data时,将忽略您的ID,因为您指定了类似id?: string; null安全模式的构造函数。

然后你得到了身份const id = a.payload.doc.id;,不知怎的,你需要按照interface的方式返回它。通过执行此操作return { id, ...data };,您将返回包含id的所有数据。并且...data将在id之后逐个追加其所有字段。您可以了解有关此功能的更多信息here希望您理解。