我对 Angular、Firestore 和 Firebase 很陌生。
我有一个组件可以获取我所有的英雄文档。我设法获取了所有英雄并将他们的名字列在列表中。我现在正在尝试获取 hero.id,以便我可以将该 id 传递给我的路由组件并显示该英雄的详细 View 。虽然我无法获得 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>
非常感谢任何帮助!谢谢! :)
最佳答案
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
管道。
关于javascript - 如何在 Firestore 数据库中检索 document.id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50078935/