首页 > 解决方案 > 将可观察数据输入其他可观察订阅

问题描述

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

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

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

    //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}}在页面上显示它时,它会返回所需的值。

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

标签: angulartypescriptfirebaserxjsobservable

解决方案


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
);

推荐阅读