【问题标题】:Add Firestore document to observable将 Firestore 文档添加到 observable
【发布时间】:2018-09-04 00:52:55
【问题描述】:
我有一个可观察的user,我想向它添加一个 Firestore 文档。现在我的 IDE 中出现错误:“类型 'DocumentData' 不可分配给类型 'Observable'。”我该怎么做?我也想听听变化。
//The observable
user: Observable<User>;
//Fetching the user, then trying to assign it to the variable
this.afs.doc(`Users/${uid}`).ref.get().then((doc)=> {
this.user = doc.data();
})
【问题讨论】:
标签:
javascript
angular
google-cloud-firestore
observable
【解决方案1】:
如果您使用 angularfire2,您可以使用 .valueChanges() 监听 Firestore 更改
user$: Observable<User> = this.afs.doc(`Users/${uid}`).valueChanges();
userSubscription: Subscription = this.user$
.subscribe((data) => {
console.log('user$ observable data: ', data);
});
如果您想包含元数据,例如文档 ID,您可以使用 .snapshotChanges() 并使用几个 maps 获取数据。
如果你使用的是 RxJS 6,它可能看起来像:
user$: Observable<User> = this.afs.doc(`Users/${uid}`)
.snapshotChanges()
.pipe(
map(changes => {
changes.map(change => {
return change.payload.doc.data();
})
})
);
userSubscription: Subscription = this.user$
.subscribe((data) => {
console.log('user$ observable data with metadata: ', data);
});
或相同的.snapshotChanges() 功能,但更短:
user$: Observable<User> = this.afs.doc(`Users/${uid}`).snapshotChanges().pipe(
map(changes => changes.map(change => change.payload.doc.data() )) );
userSubscription: Subscription = this.user$.subscribe((data) => console.log(data));