繁体   English   中英

将Firestore文档添加到可观察的

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM