首页 > 解决方案 > 如何在 Firestore 数据库中检索 document.id?

问题描述

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

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

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

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

hero.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>

任何帮助深表感谢!谢谢!:)

标签: javascriptangularfirebasegoogle-cloud-firestore

解决方案


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像现在一样使用管道。


推荐阅读