将可观察的数据馈送到其他可观察的订阅中

时间:2019-08-27 15:51:46

标签: angular typescript firebase rxjs observable

我正在创建一个应用,希望用户打开其活动聊天。它由Firebase作为后端提供动力。但是,从第一个可观察订阅中检索到数据(我需要使用该数据作为第二个可观察订阅中的参数)后,第二个订阅不返回任何数据:它为空。

在第一个订阅中,我检索一个唯一的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}}时,它将返回所需的值。

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

2 个答案:

答案 0 :(得分:2)

看着mergeMapflatMap == mergeMap),您走在正确的道路上

由于您没有提供第一个可观察到的名称,因此我将其命名为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
);

答案 1 :(得分:0)

也许您可以使用RxJS运算符连接这些可观察对象。喜欢,

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