【问题标题】:Synchronizing different method calls and return response in RxJs在 RxJs 中同步不同的方法调用和返回响应
【发布时间】:2019-02-11 20:03:26
【问题描述】:

我有一种方法可以从数据库中获取联系人数据。

this.getContact("联系人");

得到想要的输出后,我想通过下面的方法把它放到Json store中:

this.local.saveRecord("联系人", c);

一切完成后,我想借助以下方法从存储中获取保存的数据:

this.local.getRecordList("联系人")

这三个操作应该按顺序执行返回给调用者。为了实现这一点,我尝试了以下代码:

public somemethod(): Observable<Contact[]> {
return this.getContact("contact")
  .delay(1000)
  .pipe(
    concatMap(con =>
      this.local.saveRecord<Contact[]>("contact", con).delay(1000)
    )
  )
  .pipe(
    concatMap(contacts =>
      this.local.getRecordList<Contact>("contact").pipe(
        map((contacts: any[]) => {
          // Processing of data
        })
      )
    )
  );
}  

但我得到的响应总是 Null。我对 RxJs 运算符不太熟悉。如果需要,我们甚至可以跳过第二步,直接从数据库中获取数据。我应该使用不同的运算符来解决问题吗?还是我应该以不同的方式思考?帮助表示赞赏。提前致谢。

【问题讨论】:

    标签: angular typescript redux rxjs concatmap


    【解决方案1】:

    使用正确的运算符:

    public somemethod(): Observable<Contact[]> {
    return this.getContact("contact")
      .pipe(
        mergeMap(contact => this.local.saveRecord('contact', contact)),
        mergeMap(record => this.local.getRecordList('contact'))
      );
    }
    

    现在要处理数据,只需调用

    this.someService.somemethod().subscribe(contacts => {
      console.log(contacts);
    });
    

    您应该会收到来自this.local.getRecordList('contact') 的回复。是的,呼叫将被排序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      • 2017-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多