juanpalomo
juanpalomo

Reputation: 63

how to wait for http response angular

Im trying to upload a file, read it and then redirect to a component but it doesn't read the file I've try await but I dont know where to put it or if there are more solutions

component

 upload() {
 this.progress.percentage = 0; 
this.currentFileUpload = this.selectedFiles.item(0);
this.uploadService.pushFileToStorage(this.currentFileUpload).subscribe(event => {
  if (event.type === HttpEventType.UploadProgress) {
    this.progress.percentage = Math.round(100 * event.loaded / event.total);
  } 
  else  if (event.type === HttpEventType.Response) {
   
  let hud: Hud
  hud =event.body as Hud
  for (let i =0; i<this.dataService.huds.length; i++ ){
  if (this.dataService.huds[i].nombre_mesa===hud.nombre_mesa){
this.dataService.huds.splice(i,1)
}
}
this.dataService.huds.push(event.body as Hud)




  }       
});

this.selectedFiles = undefined;
}

Service

pushFileToStorage(file: File): Observable<HttpEvent<{}>> {
let formdata: FormData = new FormData();

formdata.append('file', file);

const req = new HttpRequest('POST', 'http://localhost:8080/post', formdata, {
  reportProgress: true,
  responseType: 'json'
});

return this.http.request(req);
}

Upvotes: 0

Views: 546

Answers (2)

Adil B
Adil B

Reputation: 144

pushFileToStorage(file).subscribe(event =>

switch (event.type) {
  case HttpEventType.UploadProgress:
    console.log('upload progression percentage: ', Math.round(event.loaded * 100 / event.total));
  break;
  case HttpEventType.Response:
    // upload complete.
  break;
});

Upvotes: 0

Mr Robot
Mr Robot

Reputation: 36

You can add your logic in complete this callback is call after the action response

this.uploadService.pushFileToStorage(this.currentFileUpload).subscribe({
    next: value => console.log(value),
    error: err => console.error(err),
    complete: () => console.log('DONE!')
});

Upvotes: 1

Related Questions