Http failure during parsing Angular 5

Receiving HTTP Failure during parsing in Angular. Goal is to download a csv file from the api response

Controller:

downloadFile(data) {
  const blob = new Blob([data], { type: 'text/csv' });
  const url = window.URL.createObjectURL(blob);
  window.open(url);
}

getFileDownload(): void {
  this.iportalUploadService.getFileDownload(this.fileName).subscribe(data => {
    debugger;
    this.fileDownload = data;
    this.downloadFile(data);
  });
}

Service:

private fileDownloadUrl = 'file-transfer/validationErrorsCSV';

formHtppOptions(params): any {
  const httpOptions = {
    headers: { 'Application-Token': this.getToken() },
    params: params,
  };
  return httpOptions;
}

getFileDownload(fileName): Observable < Object > {
  const baseUrl = this.getBaseUrl();
  return this.http.get<Object>(baseUrl + this.fileDownloadUrl, this.formHtppOptions({ fileName: fileName }));
}

Below is the console error I am receiving console error

Response format Photo Response photo

Answers:

Answer

You are getting this error because your response is not in JSON format. You are trying to convert it into an object and CSV text cannot be parsed to a proper json object. Here is what you might want to do:

  getFileDownload(fileName):  Observable<any> {
    const baseUrl = this.getBaseUrl();
    return this.http.get(baseUrl + this.fileDownloadUrl, this.formHtppOptions({fileName: fileName})).pipe(map((data:any) => this.converter.ToJson(data)));
  }

Usually, I have a "converter" service that does this kind of parsing. You can make use of papa parse, or parse yourself by looping through the response.

Update: Here is an example of manually parsing the response: http://blog.sodhanalibrary.com/2016/10/read-csv-data-using-angular-2.html

Have a look at the above blog post.

Answer

I resolved this issue by adding responseType: 'text' in formhttpOtions.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.