如何在Firestore数据库中检索document.id? [英] How to retrieve document.id in Firestore Database?
问题描述
我对Angular,Firestore和Firebase还是陌生的.
I am quite new to Angular, Firestore and Firebase.
我有一个可提取我所有英雄文档的组件.我设法获取了所有英雄,并在列表中列出了他们的名字.我现在正在尝试获取hero.id,以便可以将该id传递给我的路由组件,并显示该英雄的详细视图.虽然我无法获得hero.id.您如何获取文档ID?
I have a component that fetches all my hero documents. I managed to fetch all heroes and list their names in a list. I am now trying to get the hero.id so that I can pass that id to my routing component and display a detail view for that hero. Though I can not manage to get the hero.id. How do you get the document id?
我试图简单地做: hero.id ,但这似乎不起作用?
I tried to simply do: hero.id but it does not seem to work???
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>
非常感谢您的帮助!谢谢!:)
Any help is much appreciated! Thanks! :)
推荐答案
ID
在记录的元数据中.可以使用 snapshotChanges()
接收元数据(您使用 valueChanges()
).
ID
is in record's metadata. Metadata can be received with snapshotChanges()
(you use 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 };
});
});
现在您的可观察广播对象也具有 id
属性,您可以像现在一样使用 async
管道.
Now your observable broadcasts objects also with id
property and you can use async
pipe as you use now.
这篇关于如何在Firestore数据库中检索document.id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!