首页 > 解决方案 > 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);
      },
    );
  }
}

代码遍历每个层次结构:项目 -> 仪表板 -> 表格 -> 小部件。这个想法是,当每个较低层次的元素被加载时,它会被推送到上层母元素。但是在执行代码时,除了项目之外的所有对象都是未定义的。有谁知道如何解决这个问题?提前致谢。

标签: javascripttypescriptsubscription

解决方案


您应该查看订阅级别,您想要推高的数据仅存在于订阅回调中,但您想从外部使用它。还可以看看一些 rxjs 方法,例如 combinelatest switchmap 等,将这些代码拆分成其他开发人员可以使用的东西。


推荐阅读