当你调用AngularFirestore的snapshotChanges()方法时,它返回一个Observable对象,该对象会发出一个包含当前文档数据的快照。然而,该方法的行为可能看起来有些奇怪,特别是当你对文档进行更改时。
一个解决方法是使用管道操作符来转换Observable对象,以便在每次文档更改时都能获得最新的快照。你可以使用rxjs中的map操作符来实现这一点。下面是一个示例代码:
import { map } from 'rxjs/operators';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
@Component({
selector: 'app-example',
template: `
- {{ item.name }}
`
})
export class ExampleComponent {
items: Observable;
constructor(private afs: AngularFirestore) {
const collection: AngularFirestoreCollection = this.afs.collection('items');
this.items = collection.snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return { id, ...data };
});
})
);
}
}
在上面的示例中,我们使用AngularFirestoreCollection来获取一个集合的引用。然后,我们调用snapshotChanges()方法来获取该集合的快照变化。
使用管道操作符map,我们可以对快照变化进行转换。在这个例子中,我们将每个快照项转换为一个具有id和数据的对象。最后,我们将转换后的Observable对象赋值给items属性,并在模板中使用async管道来订阅并显示数据。
通过使用map操作符,我们确保在每次文档更改时都会获得最新的快照。这样,你就可以避免snapshotChanges()方法行为奇怪的问题。