[英]How to retrieve document.id in Firestore Database?
I am quite new to Angular, Firestore and Firebase. 我是Angular,Firestore和Firebase的新手。
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.
我现在正在尝试获取hero.id,以便可以将该id传递给我的路由组件,并显示该英雄的详细视图。 Though I can not manage to get the hero.id.
虽然我无法获得hero.id。 How do you get the document id?
您如何获得文件ID?
I tried to simply do: hero.id but it does not seem to work??? 我试着简单地做: hero.id,但似乎不起作用???
heroes.component.ts: 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 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
is in record's metadata. ID
在记录的元数据中。 Metadata can be received with snapshotChanges()
(you use valueChanges()
). 可以通过
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 };
});
});
Now your observable broadcasts objects also with id
property and you can use async
pipe as you use now. 现在,您的可观察广播对象也具有
id
属性,并且可以像现在一样使用async
管道。
just to know, can be like 只是知道,可以像
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.