Using HttpClient to retrieve data in formats other than JSON

Error Encountered While Trying to Download Excel File via API

I attempted to download an Excel file through an API using a specific method, but unfortunately, I encountered the following error:

SyntaxError: Unexpected token P in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad (http://localhost:5002/vendor.js:28768:51)

Here is my code snippet:

getSalesARExcel(attach: string): Observable<any>{
    const obj={
        "AttachmentId":attach
    }
    return this.http.post(baseUrl + 'api/report/aging/receivables/summary/download/xlsx', obj ,{
        headers: new HttpHeaders({
            'Content-Type': 'application/json',
            "Authorization":'Bearer ' + localStorage.getItem('token'),
            'Access-Control-Allow-Origin':'*',
            'Access-Control-Allow-Headers':'Origin, Methods, Content-Type',
            'responseType': 'ResponseContentType.Blob'
        })
    })
}

this.excel.getSalesARExcel(value.attach).subscribe(res => {
    console.log("excel", res)
    this.downloadExcelFile(res);
})

downloadExcelFile(data: any){
    var blob = new Blob([data], { type: 'application/vnd.ms-excel' });
    var url= window.URL.createObjectURL(blob);
    window.open(url);
}

Answer №1

Update the code to remove CORS headers and set responseType as an option instead of a header:

getSalesARExcel(attach: string): Observable<any>{
    const obj={
        "AttachmentId":attach
    }
    return this.http.post(url, obj ,{
        headers: new HttpHeaders({
            'Content-Type': 'application/json',
            "Authorization":'Bearer ' + localStorage.getItem('token'),
            'Access-Control-Allow-Origin':'*',
            'Access-Control-Allow-Headers':'Origin, Methods, Content-Type'
        }),
        responseType: 'blob'
    })
}

CORS headers should be used as response headers, not request headers.

The responseType should be defined as an XHR option, not a header.

For more information, check out:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it feasible to assign a value to a variable in Angular based on the data returned from a subscription?

somefunction(){ isUserLoggedin(): boolean { this.isUserInDB().subscribe((result: any) => { if (result.code === 200) { return true; } }); return false; } isUserInDB(): this API takes a token fr ...

Generating a custom type in Typescript based on specific array keys

Imagine I have a structure like this: export interface MyObject { id: number title: string } and then I create an array as shown below: const myArray: MyObject[] = [ { id: 2358, title: 'Item 1' }, { id: 85373, title: &a ...

Angular - Creating validations for numeric input fields within reactive forms to ensure values fall within a designated range

One issue I am facing in my Angular form is with a numeric input field. The requirement is to set the minimum value as 3 and the maximum value as 10. However, upon loading the form, the default value should be 0. Users are expected to enter values ranging ...

Issues with path in ngx-cookie-service while using Angular 9

I'm currently utilizing the ngx-cookie-service package to store important data for my application. It is crucial for me to save this cookie on the base path '/' so that I can easily retrieve it when needed. The cookie requires periodic updat ...

Functions outside of the render method cannot access the props or state using this.props or this.state

Just starting out with react. I've encountered an issue where a prop used in a function outside the render is coming up as undefined, and trying to use it to set a state value isn't working either. I've researched this problem and found va ...

Two unnamed objects cannot be combined using the AsyncPipe

Currently, I am looking to implement an autocomplete feature using Angular Material in Angular 8. Below is a snippet of the code used in the TypeScript file: @Input() admins: User[]; userGroupOptions: Observable<User[]>; filterFormFG: FormGrou ...

What is the process for transferring data from child components to parent components in Angular 2?

I have been thinking about the scenario where a descendant of a descendant of a parent needs to pass information back up to the parent. Would the descendant passing the information need to go through the chain back up? Descendant2 Component -> Descenda ...

Guide on integrating jQuery list filtering in Ionic 2

I stumbled upon a jQuery function that filters data in HTML, found it online. Now, I want to incorporate a similar feature into my Ionic app. However, I am unsure about the modifications required in list-search-min.js. Here is a snippet of my index.html: ...

Is it possible to duplicate a response before making changes to its contents?

Imagine we are developing a response interceptor for an Angular 4 application using the HttpClient: export class MyInterceptor implements HttpInterceptor { public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<an ...

Eliminate the eslint@typescript-eslint/no-unused-vars error in TypeScript when the index parameter is not utilized within a map function

Here's the code snippet in question: const reducer = (element:number, index: number) => [element]; //eslint-message. const positionsArray = $.map(this.positions, reducer); I am converting a Float32Array (this.positions) to a JavaScript array. The ...

Is there a method in AngularJS to compel TypeScript to generate functions instead of variables with IIFE during the compilation process with gulp-uglify?

My AngularJS controller looks like this: ArticleController.prototype = Object.create(BaseController.prototype); /* @ngInject */ function ArticleController (CommunicationService){ //Some code unrelated to the issue } I minified it using gulp: retur ...

Changing namespaces or module containers that share the same name can result in a clash

Trying to reorganize some code that was mistakenly namespaced and move it to its own namespace without affecting the current functionality during the process. The original code is structured as follows: // (org) module General.Admin.Dialogs { export cl ...

Exploring the concept of union return types in TypeScript

Hello, I am facing an issue while trying to incorporate TypeScript in a way that may not be its intended use. I have created a custom hook called useGet in React which can return one of the following types: type Response<T> = [T, false, false] | [nul ...

What is the best way to eliminate an animation from a component while using it within a different Angular Component?

I have developed an Angular Component that enhances the look of a photo with styling and animation effects. Now, I want to utilize the same styling for another component without applying the animation. Styling and Animation for the photo: .pic { position ...

Do all components in Angular 4 need to be unit tested individually?

When using Angular 4, the cli tool is included. It automatically generates files for a new component, such as the component file, template file, stylesheet, and spec file (unit test). The MainComponent serves as a placeholder for other components. The te ...

Retrieving data from a service and passing it between components in Angular 7

I have a variable called testgetinfos that holds an array of objects returned from a service. I need to access this variable in another component. Here is the function where I am retrieving the object array from a service. When I print the output of the t ...

Mastering the art of utilizing Function's construct signatures within TypeScript

Currently delving into the TypeScript documentation, specifically exploring More on Functions. However, I find myself perplexed by the code snippet provided below. Can someone offer guidance on how to implement this in practical development scenarios? An ...

How can I display the output of an API request in an Ionic 4 app's HTML page?

I have encountered an issue in Ionic 4 where I am able to successfully retrieve the results of a get response, but I am unsure how to display this data on my html page. Within my license.page.ts file: ngOnInit() { return this.httpClient.get(`${this ...

item uploaded via internet not restricted

Recently delving into Angular2, I am currently engrossed in constructing a basic application that showcases a list of objects. My goal is to click on one object and delve into a detailed view of it. However, while attempting to access the properties of the ...

Tips for preventing the appearance of a horizontal scroll bar when utilizing the FlexLayoutModule in Angular

import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-property-feed', templateUrl: './property-feed.component.html', styleUrls: ['./property-feed.component.scss'] }) export class Prope ...