javascript - 如何在 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>
任何帮助深表感谢!谢谢!:)
解决方案
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
像现在一样使用管道。
推荐阅读
- c++ - 为什么在 unique_ptr 中有一个 release()?有什么用处?
- javascript - Javascript 如何存储方法
- python - 为什么我会收到 ValueError:Series 的真值不明确?
- wordpress - 将 MariaDB 5.5.64 升级到 MariaDB 10 有必要吗?
- linux - 从正则表达式中获取文件列表
- javascript - JavaScript/D3 getFullYear() 不是函数
- matlab - 使用 fsolve 和 Euler 3BDF 的 SIR 模型
- python - Python Selenium 没有滚动到页面底部
- angular - Angular 如何在单击链接后转到页面的特定部分
- sql - Redshift SQL - 反向 Listagg 函数