在AngularFire2中,查询结果默认情况下不会返回文档ID。要获取文档ID,你可以使用snapshotChanges()
方法代替valueChanges()
方法来获取查询结果。
以下是一个示例代码,展示如何使用snapshotChanges()
来获取查询结果包含文档ID:
import { Component } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
@Component({
selector: 'app-example',
template: `
- {{ item.name }} (ID: {{ item.id }})
`,
})
export class ExampleComponent {
items: any[];
constructor(private firestore: AngularFirestore) {
this.getItems();
}
getItems() {
this.firestore.collection('items').snapshotChanges().subscribe(data => {
this.items = data.map(item => {
return {
id: item.payload.doc.id,
...item.payload.doc.data()
};
});
});
}
}
在上面的示例中,我们使用snapshotChanges()
方法来订阅文档集合的更改。然后使用map()
方法将每个查询结果转换为包含文档ID的对象。最后,我们将结果存储在items
数组中,并在模板中显示出来。
通过这种方式,你可以获取到查询结果中的文档ID。