SamCodes
SamCodes

Reputation: 394

Getting Syntax error in Response data in angular4 while trying to download an excel file

I'd like to download an excel file by clicking a button in my angular Page. When a user clicks the button, the click event triggers a service-method call:

downloadExcel(){
    this.componentService.getExel().subscribe(
        data => {
          console.log("To Download:", data);      // this part is not executed, throwing Syntax Error* shown below
          //Here, function called to download excel-file with data
        }
   );
}

The Service:

getExel(){
    let url = 'http://url/endpoint/';
    return this.httpClient.get(url);
}

**Syntax Error:

error: SyntaxError: Unexpected token P in JSON at poisition 0 at JSON.parse

In Django REST Framework Side:

class GetExcel(APIView):
    def get(self, request, format=None):
       with open('path/to/excel/file', 'rb') as tempfile:
           tempdata = tempfile()
           ResponseData = HttpResponse(tempdata, content_type='application/vnd...')
           ResponseData['Conetent-Disposition']="attachment; filename=%s" %Filename
       return ResponseData

So, I couldn't figure out where I made the mistake. And Please tell how to fix it.

Upvotes: 2

Views: 1171

Answers (2)

iPaul
iPaul

Reputation: 433

You can have a look in this post: how-to-properly-download-excel-file-with-angular2. This is more or less similar to your requirement.

Upvotes: 1

ForestG
ForestG

Reputation: 18123

...Unexpected token P in JSON at poisition 0 at JSON.parse

So in the response object, where the HTTPClient api tries to parse the response from the httpClient.get(url) call, there is a JSON format error. The problem is in the data object, but it is caused by the HTTP response itself being malformatted.

Upvotes: 1

Related Questions