【问题标题】:how to return Observables from firebase firebase function如何从 firebase firebase 函数返回 Observables
【发布时间】:2021-09-09 16:16:14
【问题描述】:

我已经完美地运行了我的应用程序

"@angular/fire": "^6.1.5",
“火力基地”:“^8.6.3”,

就像

服务.ts

getUserEventSummary(userId) {
this.firestore.collection(`/user/${userId}/event_summary`).doc('current').snapshotChanges().pipe(
      map(changes => changes.payload.data())
    );
}

组件.ts

this.service.getUserEventSummary(this.userId).subscribe((res: any) => {
    this.values = res;
}

这样的代码遍布整个应用程序。 现在我已经转移到最新版本的 firebase

"firebase": "^9.0.1", "@angular/fire": "^7.0.4",

新的变化是

service.ts

getUserEventSummary(userId) {
 return getDoc(doc(db, `user/${userId}/event_summary`, 'current'));
}

还有组件.ts

this.service.getUserEventSummary(this.userId).subscribe((docSnap: any) => {
   if (docSnap.exists()) {
        this.values = docSnap.data();;
    }
 }

我需要一个返回相同行为的方法,即该代码返回承诺的可观察对象。

此外,快照更改很难在服务文件上实现。 请帮助我找到比更改组件代码更好的方法。

【问题讨论】:

    标签: angular firebase google-cloud-firestore


    【解决方案1】:

    如果您在服务方法内部进行过滤和映射,那么您应该能够保持组件代码不变。你应该在你的服务中这样做:

    import { /* ... */, from } from 'rxjs';
    
    getUserEventSummary(userId) {
      return from(getDoc(doc(db, `user/${userId}/event_summary`, 'current'))).pipe(
        filter((docSnap) => docSnap.exists()),
        map(docSnap => docSnap.data())
      );
    }
    

    您可以使用 from 从该 Promise 对象创建一个 observable。

    【讨论】:

    • 是的,我已经尝试过了,但出现错误,“Promise>”类型上不存在属性“管道”
    • @cakePHP 你能检查我更新的答案吗?我将 Promise 转换为 Observable。
    • 能否请您也为snapshotChanges 定义方法,因为这不适用于这种方式
    • 你能检查一下the documentation,让我知道还有什么不清楚的地方吗?
    • stackoverflow.com/questions/68949123/…。请帮我解决这个问题
    猜你喜欢
    • 1970-01-01
    • 2016-09-28
    • 2021-02-12
    • 2017-08-11
    • 2018-08-04
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 2020-10-11
    相关资源
    最近更新 更多