node.js - 如何处理级联 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 字段。(并且没有错误消息)
解决方案
您可以在此处使用switchMap。
然后,当您映射结果时,您可以返回一个对象,其中包含和GetParent
的响应。GetParent
GetPerson
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;});
推荐阅读
- java - 为什么我不能将最终的 long 分配给 int?
- swift - SwiftUI:强制更新
- oracle - 用于读取嵌套 JSON 数据的 Oracle 查询
- powershell - 使用轻度匹配搜索复制位于多个子文件夹中的文件
- python-3.x - 用 theano 解决 pymc3 中的简单化学网络 odes
- pyspark - 如何在 databricks 中读取 kaggle zip 文件数据集
- html - 对齐div中的元素
- c++ - 需要澄清使用 Boost asio 的 SSL 客户端
- r - 通过循环迭代单向方差分析会在 R 中引发错误
- node.js - 为什么我在所有 meanstack 项目中不断收到相同的错误:无法加载资源:net::ERR_CONNECTION_REFUSED