gpt4 book ai didi

javascript - Angularfire2 AngularFirestoreCollection 不发送集合中每个对象的键

转载 作者:行者123 更新时间:2023-11-30 09:30:15 25 4
gpt4 key购买 nike

我正在尝试在 Angular 4 应用程序中使用 Angularfire2。我可以使用 AngularFirestoreCollection 从我的 firestore 中获取对象集合。但是,当我遍历集合中的文档时,我注意到文档不包含文档键。所以,我不认为我有任何方法可以做一些事情,比如从 UI 的列表中删除文档,因为我不知道与文档关联的 key 。这是我的代码:

  export class CategoryComponent implements OnInit {
private categoryCollection: AngularFirestoreCollection<any>;
public categories: Observable<any[]>;
public category: Category;

constructor(public db: AngularFirestore, private router: Router) {
this.categoryCollection = db.collection<any>('categories');
this.categories = this.categoryCollection.valueChanges();
this.category = new Category();
}
}

该代码为我提供了一个如下所示的集合:

{name: 'Some name'}

我期望的是:

{key: 'theKey', name: 'Some name'}

我一直在看 github 上的文档,但我要么是盲人,要么文档没有显示我做错了什么。也许我只是不知道 firebase 如何将文档发回集合中?

最佳答案

.valueChanges() 方法只会为您提供数据。如果您也需要 key ,您可以使用 .snapshotChanges()

.map((actions: any) => {
return actions.map(action => {
const data = action.payload.doc.data();
const key = action.payload.doc.id;
return {key, ...data};
});
});

为了也添加文档 key
在您的上下文中可能看起来像这样

this.categories = this.categoryCollection.snapshotChanges().map((actions: any) => {
return actions.map(action => {
const data = action.payload.doc.data();
const key = action.payload.doc.id;
return {key, ...data};
});
});

这应该会给你想要的数据

关于javascript - Angularfire2 AngularFirestoreCollection 不发送集合中每个对象的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46735252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com