【问题标题】:Observe firebase database on changes typescript观察更改打字稿的firebase数据库
【发布时间】:2018-08-12 17:24:10
【问题描述】:

所以我在这样的角度服务中调用我的 firebase 实时数据库:

readItems() {
    return this.af.database.ref(`/path`)
      .on('value', snap => this.callback(snap.val()));
  }

回调只是根据我的需要修改响应。我需要做的是在我调用readItems 的组件中获取修改后的数据。这是所述组件中的调用:

this.service.readItems();

我想知道何时完成并使用带有subscribethen 的可观察或承诺返回修改后的响应。我不知道如何做到这一点,任何帮助都会很棒。

【问题讨论】:

    标签: angular typescript firebase firebase-realtime-database angular5


    【解决方案1】:

    您可以在传递给on 函数的回调中使用来自 rxjs 的 Subject 并订阅它:

    valueChanged$ = new Subject();
    
    callback(val) {
        // some code ...
        valueChanged$.next(val); // pass whatever you need to receive in the subscription
    }
    
    readItems() {
      return this.af.database.ref(`/path`)
        .on('value', snap => this.callback(snap.val()));
    }
    

    然后在您的代码中:

    this.valueChanged$.subscribe(data => doStuff(data));
    this.service.readItems();
    

    【讨论】:

    • 这不起作用,因为 firebase.database().ref().on 不返回可观察的。见这里:firebase.google.com/docs/reference/js/…
    • 太棒了,成功了!如果您不介意,在主题变量末尾添加 $ 的原因是什么,只是常见做法?
    • 太棒了! $ 符号只是使用流和可观察对象时的约定。它让正在阅读代码的人清楚地知道它是一个流。
    • 我很高兴它有效!你也会考虑投票吗?
    • 感谢@BorisLobanov,您的回答也帮助了我,点赞:)
    猜你喜欢
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 2021-03-06
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    相关资源
    最近更新 更多