Как вызвать метод после получения ответа от ранее вызванного метода - PullRequest
2 голосов
/ 04 июня 2019

Я пытаюсь сохранить массив файлов на сервере весенней загрузки. Один файл сохраняется одновременно. я перебираю массив файлов с циклом for и делаю запрос для каждого файла, который будет сохранен. Здесь я хочу, чтобы следующий вызов был сделан только после получения ответа на первый файл. Я попробовал приведенный ниже код, но не смог его достичь.

Component.ts

public uploadNewsFiles() {

for (let index = 0; index < this.files.length; index++) {
  debugger;
  var body = new FormData();
 // alert(this.files[index].name);
  body.append('file', this.files[index]);
  this.uploading.push(true);
  this.uload(body,this.newsId,this.getFileDescriptionFormGroup(index)
  .controls['des'].value,index).then((status:any)=>
  {
    if (status.status === 'success') {
    //  alert('success');
      body.delete('file');
      this.uploading[index] = false;
      this.uploadingStatus.push(true);

    } else {
      body.delete('file');
      this.uploading[index] = false;
      this.uploadingStatus.push(false);
    }
  },(err)=>alert('failed'))
  }

   // body.append('newsId',this.newsId);
   }

  async uload(body,newsId,desc,index) {
  return await this.service.saveFiles(body, newsId,desc).toPromise();
  }

service.ts

public saveFiles(body,newsId,des) {

return this.http.post(this.url + '/saveFiles? 
newsId='+newsId+'&fileDescription='+des,body);
}

Ответы [ 2 ]

0 голосов
/ 04 июня 2019

Поскольку вы используете Angular, мы можем воспользоваться библиотекой rxjs и вместо использования toPromise и связать наблюдаемые из вызова http, что-то вроде:

function modUploadFiles() {
  this.files
    .map((file, index) => {
      const body = new FormData();
      body.append("file", file);

      const newsId = this.newsId;

      const desc = this.getFileDescriptionFormGroup(index).controls["des"]
        .value;

      return this.service.saveFiles(body, newsId, desc).finally(status => {
        body.delete("file");
        this.uploading[index] = false;
        this.uploadingStatus.push(status.status === "success");
      })
    })
    .reduce((acc, next) => acc.flatMap(() => next))
    .subscribe(result => {/*Do something*/});
}

Вы можете увидеть большеинформация в следующем вопросе:

Наблюдаемые цепочки в RxJS

0 голосов
/ 04 июня 2019

вы можете использовать async await.

async uploadNewsFiles() {

for (let index = 0; index < this.files.length; index++) {
  var body = new FormData();
  body.append('file', this.files[index]);
  this.uploading.push(true);
  await this.uload(body,this.newsId,this.getFileDescriptionFormGroup(index)
  .controls['des'].value,index).then((status:any)=>
  {
     if (status.status === 'success') {
       body.delete('file');
       this.uploading[index] = false;
       this.uploadingStatus.push(true);
// here we are calling the 
     } else {
       body.delete('file');
       this.uploading[index] = false;
       this.uploadingStatus.push(false);
     }
    },(err)=>alert('failed'))
  }
}

uload(body,newsId,desc,index) {
  return new Promise((resolve, reject) => {
     this.service.saveFiles(body, newsId,desc).toPromise().then(resp => {
        resolve(resp); // here we are resolving our promise
     });
  });
}

Сервис

public saveFiles(body,newsId,des) {
 return this.http.post(this.url + '/saveFiles? 
         newsId='+newsId+'&fileDescription='+des,body);
}

Надеюсь, это вам поможет.

...