如何将文档添加到 Firestore 和 return Observable<T>
How to add document to Firestore and return Observable<T>
使用@angular/fire returns 承诺将文档添加到 Firestore 集合。我想要做的是添加文档,然后 return 创建文档的 Observable。到目前为止,这是我尝试过的方法:
colRef: AngularFirestoreCollection = this.afs.collection<Session>('sessions');
add(session: Session): Observable<Session> {
return this.colRef.add(session).then((docRef) {
return this.colRef.doc<Session>(docRef.id).valueChanges();
})
}
当然这不行,它正在尝试return一个Promise<Observable<Session>>
。我知道为什么 它不起作用,但不知道如何实现我所追求的目标。非常感谢任何帮助!
您可以使用 RxJS from
method with switchMap
运算符。尝试以下
import { from } from 'rxjs';
import { switchMap } from 'rxjs/operators';
add(session: Session): Observable<Session> {
return from(this.colRef.add(session)).pipe(
switchMap((docRef) => this.colRef.doc<Session>(docRef.id).valueChanges());
);
}
from
可用于将 promise 转换为 observable。
使用@angular/fire returns 承诺将文档添加到 Firestore 集合。我想要做的是添加文档,然后 return 创建文档的 Observable。到目前为止,这是我尝试过的方法:
colRef: AngularFirestoreCollection = this.afs.collection<Session>('sessions');
add(session: Session): Observable<Session> {
return this.colRef.add(session).then((docRef) {
return this.colRef.doc<Session>(docRef.id).valueChanges();
})
}
当然这不行,它正在尝试return一个Promise<Observable<Session>>
。我知道为什么 它不起作用,但不知道如何实现我所追求的目标。非常感谢任何帮助!
您可以使用 RxJS from
method with switchMap
运算符。尝试以下
import { from } from 'rxjs';
import { switchMap } from 'rxjs/operators';
add(session: Session): Observable<Session> {
return from(this.colRef.add(session)).pipe(
switchMap((docRef) => this.colRef.doc<Session>(docRef.id).valueChanges());
);
}
from
可用于将 promise 转换为 observable。