How to cast event to return HttpEventType.Response when subscribe data?

2.7k views Asked by At

I work on angular 8 I face issue I can't cast event to return HttpEventType.Response when subscribe data to get progress bar upload

component service

PostUpload(selectedoptionsId, file)
{
  const formData: FormData = new FormData();
  formData.append('file', file,file.name);
  formData.append('selectedoptions',selectedoptionsId.toString());
 return this.http.post('http://localhost:61265/api/DeliverySys/', formData,{responseType: 'blob'});
}

component type script

this._dataService.PostUpload(this.selectedoptions.toString(),this.fileToUpload)
     .subscribe((event:any) => {
      if (event.type === HttpEventType.Response) {
          console.log('Upload complete');
    }
    })

event.type always return "text/plain" on debugger and event is BLOB so How to cast it to return HttpEventType.Response

update original post

what I try as below :

this._dataService.PostUpload(this.selectedoptions.toString(),this.fileToUpload)

 .subscribe((event: HttpEvent<any>) => {

  switch (event.type) {

    case HttpEventType.Sent:

      console.log('Request has been made!');

      break;

    case HttpEventType.ResponseHeader:

      console.log('Response header has been received!');

      break;

    case HttpEventType.UploadProgress:

      this.progress = Math.round(event.loaded / event.total * 100);

      console.log(`Uploaded! ${this.progress}%`);

      break;

    case HttpEventType.Response:

      console.log('User successfully created!', event.body);

      this.message='User successfully created!';

      saveAs(event, this.fileToUpload.name + '.xlsx')

      setTimeout(() => {

        this.progress = 0;

      }, 1500);



  }

})



file not saved and this console give me



Request has been made!

 Uploaded! 100%

Response header has been received!



core.js:4002 ERROR HttpErrorResponse

image issue

error i get as above is

HttpErrorResponse
error: {error: SyntaxError: Unexpected token P in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "PK\u0003\u0004\u0014\u0000\b\b\b\u0000�u\u000eSH7b�X\u0001\u0000\u00000\u0006\u0000\u0000\u0013\u0000\u0000\u0000[Content_Types].xml�…\u0000\u0000\u0000�\u001a\u0000\u0000xl/sharedStrings.xmlPK\u0005\u0006\u0000\u0000\u0000\u0000\r\u0000\r\u0000R\u0003\u0000\u0000O\u001d\u0000\u0000\u0000\u0000"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:61265/api/DeliverySys/"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:61265/api/DeliverySys/"
[[Prototype]]: HttpResponseBase

response header

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Content-Disposition: attachment; filename=Orignal2-4108965c-60d8-4b12-a5a9-80a7fa038479.xlsx; filename*=UTF-8''Orignal2-4108965c-60d8-4b12-a5a9-80a7fa038479.xlsx
Content-Length: 8375
Content-Type: text/plain
Date: Sat, 14 Aug 2021 13:00:28 GMT
Server: Kestrel
Vary: Origin
1

There are 1 answers

11
xTheDoctah On BEST ANSWER

If I got the question right, you have to create your request like so:

  addUser(name: string, profileImage: File): Observable<any> {
    var formData: any = new FormData();
    formData.append("name", name);
    formData.append("avatar", profileImage);

        return this.http.post('http://localhost:61265/api/DeliverySys/',formData,{
          reportProgress: true,
          observe: 'events'//now when you will subscribe you will get the events, in his case he neded responseType: 'blob', because from the back end he was receiving the blob too.
        });
   }
    

Then just the call the method like so:

this.fileUploadService.addUser(
  this.form.value.name,
  this.form.value.avatar
).subscribe((event: HttpEvent<any>) => {
  switch (event.type) {
    case HttpEventType.Sent:
      console.log('Request has been made!');
      break;
    case HttpEventType.ResponseHeader:
      console.log('Response header has been received!');
      break;
    case HttpEventType.UploadProgress:
      this.progress = Math.round(event.loaded / event.total * 100);
      console.log(`Uploaded! ${this.progress}%`);
      break;
    case HttpEventType.Response:
      console.log('User successfully created!', event.body);
     //add whatever thing you have to do here. 
      setTimeout(() => {
        this.progress = 0;
      }, 1500);

  }
})

Here the source