在可观察对象内执行可观察对象中的操作

时间:2019-07-02 17:34:26

标签: angular typescript rxjs

我正在尝试在另一个.subscribe()内的.subscribe()中执行操作:收集文件,以便之后都可以将其全部压缩。

我正在使用JSZip处理代码的“压缩”部分。

我已经尝试使用.map()而不是遍历for循环。我在这里(Is it good way to call subscribe inside subscribe?阅读,我可以使用.flatMap()解决问题,因为我的第二个Observable(下载文件)取决于第一个(可获取文件)的结果,但是我仍然无法不知道...

我目前有一个正在运行的实现,但是它使用setTimeout(),因此它“等待”文件被下载,因此我可以对其进行压缩,但是我认为这不是最好的方法。

    this.downloadingZipFile = true;
    let zip = new JSZip();
    let tableTemplateCollection = '';
    let givenName = this.patientGivenName;

    let templateIndex = zipTemplate.templateIndex; 

    console.log('TOTAL FILES COUNT: ' + this.totalFiles);
    this.fileViewerDataService.getFileNamesList(this.patient.getPatientQueryParams(), this.totalFiles, 0)
      .subscribe((data) => {
        let dataLength = Object.keys(data).length;
        for (let i = 0; i < dataLength; i++) {
          console.log('THIS IS THE ID: ' + data[i]['indexId']);
          this.fileViewerDataService.getFileViewByIdAsBlob(data[i]['indexId']).subscribe(patientFile => {
            console.log(`Saving... ${data[i]['indexId']}`);
            if ((data[i]['name']).includes('immunization')) {
              console.log('THIS IS THE PATIENT FILE: ' + patientFile);
              zip.folder('immunization').file(`${data[i]['name']}.html`, patientFile);
              tableTemplateCollection += this.indexCreation(data[i]['name']);
            } else if ((data[i]['name']).includes('laboratory')) {
              console.log('THIS IS THE PATIENT FILE: ' + patientFile);
              zip.folder('laboratory').file(`${data[i]['name']}.html`, patientFile);
              tableTemplateCollection += this.indexCreation(data[i]['name']);
            } else {
              console.log('THIS IS THE PATIENT FILE: ' + patientFile);
              zip.folder('medication').file(`${data[i]['name']}.html`, patientFile);
              tableTemplateCollection += this.indexCreation(data[i]['name']);
            }
            this.downloadingZipFile = false;
          });
        }
        setTimeout(function () {
          templateIndex = templateIndex.replace('##NAME##', givenName);
          tableTemplateCollection = templateIndex.replace('##FILES##', tableTemplateCollection);
          zip.file('index.html', tableTemplateCollection);
          zip.file('data.js', translateEnFr.data);
          zip.generateAsync({ type: "blob" }).then(function (patientFolders) {
            saveAs(patientFolders, "Report.zip");
          });
        }, 2500);
      },
        err => {
          window.alert(`${err.status}: Error downloading zip from API.`);
        })
  }

1 个答案:

答案 0 :(得分:0)

您肯定是正确的,setTimeout()不是最好的方法。您可以使用如下承诺:

this.fileViewerDataService.getFileNamesList(this.patient.getPatientQueryParams(), this.totalFiles, 0)
  .subscribe((data) => {
    let dataLength = Object.keys(data).length;
    let promises = [];
    for (let i = 0; i < dataLength; i++) {
      console.log('THIS IS THE ID: ' + data[i]['indexId']);
      promises.push(createPromise(data[i]));
    }
    Promise.all(promises).then(() => {
      templateIndex = templateIndex.replace('##NAME##', givenName);
      tableTemplateCollection = templateIndex.replace('##FILES##', tableTemplateCollection);
      zip.file('index.html', tableTemplateCollection);
      zip.file('data.js', translateEnFr.data);
      zip.generateAsync({ type: "blob" }).then((patientFolders) => saveAs(patientFolders, "Report.zip"));
    }).catch(err => {
      window.alert(`${ err.status }: Error downloading zip from API.`);
    });
  },
    err => {
      window.alert(`${ err.status }: Error downloading zip from API.`);
    });

createPromise()看起来像这样:

createPromise(data) {
  return new Promise((resolve, reject) => {
    this.fileViewerDataService.getFileViewByIdAsBlob(data['indexId']).subscribe(patientFile => {
      console.log(`Saving... ${ data['indexId'] }`);
      if ((data['name']).includes('immunization')) {
        console.log('THIS IS THE PATIENT FILE: ' + patientFile);
        zip.folder('immunization').file(`${ data['name'] }.html`, patientFile);
        tableTemplateCollection += this.indexCreation(data['name']);
      } else if ((data['name']).includes('laboratory')) {
        console.log('THIS IS THE PATIENT FILE: ' + patientFile);
        zip.folder('laboratory').file(`${ data['name'] }.html`, patientFile);
        tableTemplateCollection += this.indexCreation(data['name']);
      } else {
        console.log('THIS IS THE PATIENT FILE: ' + patientFile);
        zip.folder('medication').file(`${ data['name'] }.html`, patientFile);
        tableTemplateCollection += this.indexCreation(data['name']);
      }
      this.downloadingZipFile = false;
      resolve();
    }, error => reject(error));
  });
}
相关问题