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

2024-05-13

这是我的代码:

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

}

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

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

您正在获取可观察的数据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() and .snapshotChanges()。 valueChanges() 方法仅提供数据。它会删除所有元数据,包括keys。另一方面 .snapshotChanges() 将返回包括元数据在内的所有数据。

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

然后你就得到了idconst id = a.payload.doc.id;不知怎的,你需要以你想要的方式归还它interface是。通过做这个return { id, ...data };您也将返回带有 id 的所有数据。和...data会将其所有字段一一追加到 id 之后。您可以了解有关此功能的更多信息here https://odetocode.com/blogs/scott/archive/2014/09/02/features-of-es6-part-5-the-spread.aspx希望你能理解。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何检索单个 Firestore 文档的 Id? 的相关文章

随机推荐