首页 > 解决方案 > 2个for循环完成后如何返回值?

问题描述

我的代码在数据库中进行 for-loop 查询并在前端进行计算。

如何仅在计算完成并且所有 for 循环都完成时才显示值?

这是我的过程:

startQuery() {
    this.loading = true;

    const queryInfo = {
      //from form field
    }

    this.report = {};

    //first DB query
    this.angularService.getTime(queryInfo).subscribe(data => {

      const first = data.accounts;

      for (let i = 0; i < first.length; i++) {

        this.report[first[i].firstName] = {
          firstName: first[i].firstName,
        };

        const totalDays = 30;
        for (let dayNum = 0; dayNum <= totalDays; dayNum++) {

          const employeeId = first[i].eeid;

          //Second query from DB
          this.angularService.getTimeRecord(employeeId, ).subscribe(data => {

            //process data 

          })
        }
      }

      this.resultDetails = []

      for (var subObj in this.report) {
        this.resultDetails.push(this.report[subObj]);
      }
    })

    this.loading = false;
}

在我的 html 中,如果 this.loading = true,则应该显示微调器,并且仅当 this.loading 为 false 时才显示值。结果是 Spinner 暂时显示并显示值,但是,显示通常不完整。在显示的值完成之前,我必须单击 startQuery 按钮 2 或 3 次。

如何确保在显示值之前完成所有数据库查询和前端计算?

标签: typescriptangular8

解决方案


startQuery() {
    this.loading = true;

    const queryInfo = {
      //from form field
    }

    this.report = {};

    //first DB query
    this.angularService.getTime(queryInfo).subscribe(data => {

      const first = data.accounts;

      for (let i = 0; i < first.length; i++) {

        this.report[first[i].firstName] = {
          firstName: first[i].firstName,
        };

        const totalDays = 30;
        let responseCount = 0;
        for (let dayNum = 0; dayNum <= totalDays; dayNum++) {

          const employeeId = first[i].eeid;

          //Second query from DB
          this.angularService.getTimeRecord(employeeId, ).subscribe(data => {
              responseCount ++;
              if (responseCount == totalDays){
                   this.loading = false;
               }
            //process data 

          })
        }
      }

      this.resultDetails = []

      for (var subObj in this.report) {
        this.resultDetails.push(this.report[subObj]);
      }
    })
}

推荐阅读