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

Jac*_*wyk 5 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() {}

}
Run Code Online (Sandbox Code Playgroud)

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

Observable {_isScalar: false, source: Observable, operator: MapOperator}
Run Code Online (Sandbox Code Playgroud)

Har*_*esh 13

您正在获取Observable数据 const data = a.payload.doc.data() as Country

你需要订阅才能获得数据

this.docId.subscribe(docs => {
  docs.forEach(doc => {
    console.log(doc.id);
  })
})
Run Code Online (Sandbox Code Playgroud)

这是推荐的方法

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

}
Run Code Online (Sandbox Code Playgroud)

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

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

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