javascript - Javascript从http请求加载和映射数据
问题描述
在我的应用程序中,我有一个带有处理所有数据库条目的休息接口的服务器。当用户登录应用程序时,应加载所有用户数据并将其从数据库模型映射到可用模型。不同之处在于,数据库模型只保存其子对象的 id,而普通模型直接继承其子对象。因此,要通过来自数据库的 http 请求加载所有对象并映射它们,我构建了这个:
class SomeClass {
private loadProjectData(projectId: string): void {
let s: Sheet;
let d: Dashboard;
this.databaseService.getDocument("Projects", projectId).subscribe(
(project: ProjectDB) => {
this.project = new Project(project.id, project.name, project.theme, []);
for (const dash of project.dashboards) {
this.databaseService
.getDocument("Dashboards", dash)
.subscribe((dashboard: DashboardDB) => {
d = new Dashboard(dashboard.id, dashboard.name, []);
for (const shee of dashboard.sheets) {
this.databaseService
.getDocument("Sheets", shee)
.subscribe((sheet: SheetDB) => {
s = new Sheet(sheet.id, sheet.name, []);
for (const wid of sheet.widgets) {
this.databaseService
.getDocument("Widgets", wid)
.subscribe((widget: WidgetDB) => {
// TODO check widget type
s.widgets.push(
new Widget(
widget.id,
widget.name,
widget.position,
widget.isDeveloped,
widget.type,
),
);
this.dataService.changeProjectData(this.project);
});
}
});
}
d.sheets.push(s);
this.dataService.changeProjectData(this.project);
});
this.project.dashboards.push(d);
this.dataService.changeProjectData(this.project);
}
console.log("Project", this.project);
this.router.navigate(["dashboard"]);
},
err => {
console.log("Error loading project data from database ", err);
},
);
}
}
代码遍历每个层次结构:项目 -> 仪表板 -> 表格 -> 小部件。这个想法是,当每个较低层次的元素被加载时,它会被推送到上层母元素。但是在执行代码时,除了项目之外的所有对象都是未定义的。有谁知道如何解决这个问题?提前致谢。
解决方案
您应该查看订阅级别,您想要推高的数据仅存在于订阅回调中,但您想从外部使用它。还可以看看一些 rxjs 方法,例如 combinelatest switchmap 等,将这些代码拆分成其他开发人员可以使用的东西。
推荐阅读
- c - 函数及其在 main 之外的定义不起作用
- angular - Angular未进入自定义表单验证
- python - 在 Firefox 机器人框架上接受 facebook cookie
- javascript - 使用参数回调函数
- python - 如何防止在 Python 中引发自定义异常?
- typescript - 如果我们使用猫鼬,我们应该在nestJS中使用没有typeorm的实体吗
- python - 如何加速用于迭代行以查找匹配的 ID 号并从中提取数据的循环
- python - 如何在 matplotlib 中显示 sympy 方程
- c++ - C++ 数组的地址和值的关系?
- linux - 带 gp 的 openconnect 不会在命令行中提示进行 SAML 身份验证