【问题标题】:Feed observable data into other observable subscription将可观察数据输入其他可观察订阅
【发布时间】:2019-12-31 20:24:51
【问题描述】:

我正在创建一个应用并希望用户打开他们的活跃聊天。它由 Firebase 作为后端提供支持。但是,在从第一个 observable 订阅中检索数据后,我需要将其用作第二个 Observable 订阅中的参数,第二个订阅不返回任何数据:它是空的。

在第一次订阅中,我检索了一个唯一的 ChatID。通过第二次订阅,我希望使用此 ChatID 接收来自 Firebase 集合的所有消息。

我已经发现它与 observable 的异步风格有关,但我不知道如何嵌套 observable,因为 FlatMap 和 MergeMap 都不适用于我的 observable。

    //First subscription
    this.ActieveGebruikerObservable = this.firebaseService.Gebruiker_lezen(this.ActieveGebruiker.uid);
    this.ActieveGebruikerObservable.subscribe(
      val => this.ActieveGebruikerDetails = val
    );

    //Second subscription
    this.ActieveChatObservable = this.firebaseService.Chat_lezen(this.ActieveGebruiker.uid, this.ActieveGebruikerDetails.ActieveChat);
    this.ActieveChatObservable.subscribe(
      val => this.ActieveChatDetails = val
    );

因此,当作为参数输入第二个订阅时,this.ActieveGebruikerDetails.ActieveChat 似乎是空的。但是,当我在页面上将其显示为{{this.ActieveGebruikerDetails.ActieveChat}} 时,它会返回所需的值。

我想检索第二个订阅数据,而不是空白数据。

【问题讨论】:

  • 我认为你的一些代码被砍掉了。你能多发一些关于 ActieveGebruiker 和 ActieveGebruikerDetails.ActieveChat 的设置吗?

标签: angular typescript firebase rxjs observable


【解决方案1】:

您在查看mergeMap (flatMap == mergeMap) 时走在正确的道路上

由于您没有给出第一个 observable 的名称,我将其命名为 foo

foo.pipe(
    tap(val => this.ActieveGebruikerDetails = val), // If you still wanted it present on `this`, but not needed
    mergeMap(val => this.firebaseService.Chat_lezen(this.ActieveGebruiker.uid,val.ActieveChat) // map to the firebase observable, using the value from the previous observable, allowing you to access ActieveChat
).subscribe(
  val => this.ActieveChatDetails = val
);

【讨论】:

  • 那行得通!非常感谢,这几天一直在苦苦挣扎。
【解决方案2】:

也许你可以使用 RxJS 操作符来连接这些 observables。喜欢,

Someservice.switchMap(val => { this.ActieveGebruikerDetails = val; 返回 this.firebaseService.Chat_lezen(this.ActieveGebruiker.uid, this.ActieveGebruikerDetails.ActieveChat); }) .subscribe(val => this.ActieveChatDetails = val);

【讨论】:

    猜你喜欢
    • 2019-07-07
    • 2018-11-26
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多