[英]Add Firestore document to observable
我有一個可觀察的user
,我想向其中添加一個Firestore文檔。 現在,我在IDE中遇到錯誤:“類型'DocumentData'無法分配給類型'可觀察'。” 我該怎么做? 我也想聽聽變化。
//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();
})
如果您使用的是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()
並使用一些map
獲得數據。
如果您使用的是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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.