'Download excel with Angular 11

I am trying to download an excel from backend api. I only get the response : error: SyntaxError: Unexpected token P in JSON at position 0 at JSON.parse () message: "Unexpected token P in JSON at position 0"

getAllUsersToExcel(jwt:string)
 {

   const headers = new HttpHeaders({
     'content-type' : 'application/json',
     'Access-Control-Allow-Origin' : '*',
     'Authorization' : `Bearer ${jwt}`

   });

   const httpHeaders = new HttpHeaders({
     'Authorization' : `Bearer ${jwt}`
   });

   const options = {
     headers: headers,
     responseType: 'arrayBuffer'
     };
     return this.http.get<ArrayBuffer>(`${this.baseUrlAdmin}/users/all/excel`, {headers: httpHeaders} )
       .subscribe(blob => saveAs(blob, 'users.xlsx'))
   // return this.http.post<ArrayBuffer>(`${this.baseUrlAdmin}/users/all/excel`, [], {options});
   // return this.http.post<ArrayBuffer>(`${this.baseUrlAdmin}/users/all/excel`,[], {options});
   // {headers: {'Authorization' : `Bearer ${jwt}`, responseType: "blob"}
 }

If iput responseType outside header I get : No overload matches this call. Overload 1 of 15, '(url: string, option

My spring boot controller looks likes this:

@GetMapping("users/all/excel")
    public ResponseEntity<Resource> getAllExamUsersExcel()
    {
        log.info("Get all users");
        String filename = "examtakers.xlsx";
        InputStreamResource file = new InputStreamResource(adminService.getAllExamUsersAsExcel());
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename)
                .contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
                .body(file);
    }

I cannot change to a tag in the frontend as i have authenication.



Solution 1:[1]

Solved it with responseType: 'blob' as 'json'

getAllUsersToExcel(jwt:string) {  
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization' : `Bearer ${jwt}`
    }); 
    
    return this.http.post<Blob>(`${this.baseUrlAdmin}/users/all/excel`,
      {}, {headers: headers, responseType: 'blob' as 'json' })
      .subscribe(
        (val) => { 
          saveAs(val);
        },
        response => {
          console.log("POST in error", response);
        },
        () => {
          console.log("POST observable is now completed.");
        });;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Caspar