首页 > 解决方案 > 如何处理级联 observable

问题描述

我很难掌握事物与可观察对象的工作方式。我正在开发一个 API 来检索一个具有多个属性和两个“父级”的“人”。我正在使用返回 observables 的 mssql 模块检索这些对象。我的问题是,当我获得 Observable 时,我无法获得一个“父”对象来填充我的函数返回的“Person”(因为我正在获得另一个 Observable)。

我知道 map 运算符允许我编辑发出的值以在 Person ID 的帮助下填充父母字段。但似乎两个 Observable 无法在 map 运算符中订阅:我的函数返回 Observable 而不等待父母被填充。

return this.SQLService.GetPerson().pipe(
  map((p: any): Person => {
    // This fills the Person object from the db returned object
    let returnValue = new Person(p);
    this.SQLService.GetParent(returnValue.ID).pipe(
      map((parentObj: any): Parent => { return new Parent(parentObj); })
    ).subscribe(
      (parentInstance: Parent): void => {returnValue.Parent1 = parentInstance;}
    );
  return returnValue;
})

来自同步开发,我希望我的 returnValue 实际上返回一个 Person ,其中包含一个包含父级的 Person.Parent1 字段。最后,我可以得到 Person,但没有 Parent1 字段。(并且没有错误消息)

标签: node.jsasynchronousrxjsobservablenestjs

解决方案


您可以在此处使用switchMap

然后,当您映射结果时,您可以返回一个对象,其中包含和GetParent的响应。GetParentGetPerson

return this.SQLService.GetPerson().pipe(
  switchMap((p: any): Person => {
    // This fills the Person object from the db returned object
    let returnValue = new Person(p);
    return this.SQLService.GetParent(returnValue.ID).pipe(
      map((parentObj: any): Parent => { return { parent: new Parent(parentObj), returnValue }; })
    );
  }),

).subscribe(({ parent, returnValue }): void => {returnValue.Parent1 = parentInstance;});

推荐阅读