【问题标题】:Javascript loading and mapping data from http requestJavascript从http请求加载和映射数据
【发布时间】:2019-03-15 00:27:29
【问题描述】:

在我的应用程序中,我有一个带有处理所有数据库条目的休息接口的服务器。当用户登录到应用程序时,应加载所有用户数据并将其从数据库模型映射到可用模型。不同的是,数据库模型只保存其子对象的 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);
      },
    );
  }
}

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

【问题讨论】:

    标签: javascript typescript subscription


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2011-01-10
      • 1970-01-01
      • 2012-06-06
      • 1970-01-01
      • 1970-01-01
      • 2015-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多