【问题标题】:How to retrieve document.id in Firestore Database?如何在 Firestore 数据库中检索 document.id?
【发布时间】:2018-10-09 06:36:16
【问题描述】:

我对 Angular、Firestore 和 Firebase 还是很陌生。

我有一个组件可以获取我所有的英雄文档。我设法获取了所有英雄并将他们的名字列在一个列表中。我现在正在尝试获取 hero.id,以便我可以将该 id 传递给我的路由组件并显示该英雄的详细视图。虽然我无法获得 hero.id。如何获取文档 ID?

我试图简单地做:hero.id,但它似乎不起作用???

heroes.component.ts:

import { Component, OnInit } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {

  heroes: Observable<any[]>;

  constructor(db: AngularFirestore){
    this.recipes = db.collection('heroes').valueChanges();
  }

  ngOnInit() {
  }
}

heroes.component.html

<ul>
  <li class="text" *ngFor="let hero of heroes | async">
    <a routerLink="/hero/{{hero.id}}">{{hero.name}} -> id: {{hero.id}}</a>
  </li>
</ul>

非常感谢任何帮助!谢谢! :)

【问题讨论】:

标签: javascript angular firebase google-cloud-firestore


【解决方案1】:

才知道,可以喜欢

getHeroes = async () => {
        try {
            const heroes= [];

            var ret = await db.collection('heroes').get();

            ret.docs.map((e) => {
                heroes.push({id: e.id, ...e.data()});
            });

            console.log(heroes);

        } catch (e) {
            console.log(e);
        }
}

【讨论】:

    【解决方案2】:

    ID 在记录的元数据中。可以使用snapshotChanges() 接收元数据(您使用valueChanges())。

    this.recipes = db.collection('heroes').snapshotChanges().map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data();
        const id = a.payload.doc.id;
        return { id, ...data };
      });
    });
    

    现在您的 observable 广播对象也具有 id 属性,您可以像现在一样使用 async 管道。

    【讨论】:

      猜你喜欢
      • 2021-10-26
      • 2020-12-17
      • 2021-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-12
      • 2020-08-08
      • 2019-08-07
      相关资源
      最近更新 更多