Extract headers from an HTTP GET request in Angular

Currently, I am working on a project that involves making API calls to retrieve blob data.

The backend also sends the file name in the header, which is causing some issues for me as I am unable to access the header from the API response.

Below is my code snippet from service.ts:

public openFile(path) {
  let url = '/download/';
  let pathFile = new HttpParams().set('pathFile', path);
  return this.httpClient.get(url, { params: pathFile, responseType: 'blob' });

Within the component.ts, I am calling the service. However, when attempting to print res.headers, I am only seeing 'undefined' in the console:

openFile(path){
  this.creditPoliciesService.openFile(path).toPromise().then (data => {
    console.log("dataaaaaa",data.headers); // undefined
    var blob = new Blob([data], {type: 'application/pdf'}); 
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob);
    }
    else {
      var fileURL = URL.createObjectURL(blob); 
      window.open(fileURL);
    }
  });
}

Although the developer tools show information in the response headers, I am struggling to access them within the response variable.

Answer №1

To retrieve the full response, remember to pass the observe key with a value of 'response'

fetchData() {
 this.http.get(this.url, { observe: 'response' }).subscribe(result => {
   this.customProperty = result.headers.get('specific property name');
 });
}

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

Retrieving the input value using ref in Vue 3 and TypeScript

It appears to be a straightforward issue, but I haven't been able to find consistent Vue 3 TypeScript documentation on accessing an input field and retrieving its value from within a function. <template> <Field type="text" ...

Issue with VS2017RC: TypeScript fails to produce JavaScript files

After updating to VS 2017, I noticed that modifications made to a typescript file no longer result in the generation of any javascript code, despite receiving a message indicating "outputs generated successfully" on the lower bar. I tested this issue on t ...

Organizing a vast TypeScript project: Comparing Modules and Namespaces

As someone relatively new to TypeScript, I am currently working on a small prototyping framework for WebGl. During my project refactoring, I encountered challenges in organizing my code, debating between using modules or namespaces as both have their drawb ...

Encountered React error: Cannot assign type 'string | string[]' to type 'string[]'

I am brand new to React but have a good grasp on vanilla JS, and I've been following a YouTube tutorial. The tutorial took a different approach in this section which is why I need some guidance. Essentially, I'm defining an 'interface ListP ...

Locating Items in an Array using Angular 5 and Forming a New Array with the Located Objects

Looking for a way to extract objects from an array that have the type "noActiveServiceDashboard" and "extraAmountDashboard". I want to create a new array with only these two entries in the same format. I've attempted using .find() or .filter() method ...

Steps for implementing an onclick action in Angular 4 from infowindow content

Currently, I am integrating Google Maps into an Angular 4 project and I need to implement a click event inside the infowindow. How can I achieve this? I attempted the following code but encountered an issue where the name is undefined. Even though I called ...

The property 'licenses' has incompatible types. The type 'License[]' cannot be assigned to type 'undefined' in the getServerSideProps function while using iron-session

I am encountering an issue with red squiggly lines appearing on the async keyword in my code: Argument of type '({ req, res }: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>) => Promise<{ props: { admin: Admin; licenses?: undefined ...

Although the cucumber tests indicate success, protractor fails to interact with the elements on the webpage

Recently, I delved into the realm of Protractor+Cucumber+Typescript and devised a sample framework utilizing Page Object Design along with a small script to execute some click actions. URL: My endeavor to click on the "Customer Login" button seems futile ...

Steps to retrieve the final page number from ngx-pagination with Angular

Is there a way to utilize Custom templates within ngx-pagination in order to ensure that the first and last buttons function properly when clicked? Currently, I have utilized pagination-template to accomplish this... How can I dynamically determine the la ...

Elastic Beanstalk hosted apps do not support the transmission of large files

I've been working on a web application that requires storing large files, specifically mp4 videos with sizes sometimes exceeding 100mb. However, I encountered an error when trying to upload these files from a static Angular website hosted in an S3 buc ...

The Angular application runs smoothly on my computer, but I encounter an error saying "ERROR [node 6/6] RUN npm run build --prod" after I create a Docker image

My DockerFile includes the following commands, along with a .dockerignore file excluding (node_modules; .gitignore). #stage 1 FROM node:alpine as node WORKDIR /app COPY . . RUN npm install #RUN npm install -g @angular/<a href="/cdn-cgi/l/email-protecti ...

What is the best way to verify that an error was triggered within a flatMap function?

Unit testing is being done to ensure that an error is triggered when a specific type property does not match any case in a switch statement. The function containing the throw action is nested within a series of flatMaps and concludes with a subscribe opera ...

The higher-level modules in Angular 2 are having trouble locating their declarations

I have a cascading module structure, categorized by different features: /app /lib (not considered a module) /pipes capitalize.pipe.ts /portal /dashboard /public Each module is designed to be lazily loaded with their own routes. Below ...

Bring Jest into everyday script

Can Jest be imported into a file that is not intended to run as a test and does not include any test cases (such as a support module for tests)? ...

Mistakes following the modification of tsconfig.json and package.json

Recently, I delved into exploring the Ahead-of-time compilation cookbook for Angular and found it quite intriguing. However, it seems like the errors I am encountering are not directly related to my new venture. You can check out the cookbook here: https:/ ...

Find the identifier that does not currently exist in the collection of objects

There is a situation where I have an array and an object that consists of arrays of ids, which are essentially permission objects. My goal now is to extract the ids that do not exist in the given object. Can someone assist me with devising the necessary l ...

Typescript generates a warning when utilizing JSON objects in conjunction with data types

Attempting to access the attributes of a JSON object within a hook using bracket notation. Although it seems to be functioning correctly, TypeScript continues to throw this warning: Property 'github' does not exist on type 'PropertyValues& ...

Determining the return type by analyzing the parameter type

I'm currently struggling to find the correct way to define this function in order for all four "tests" that come after it to pass. I've experimented with different function overloads and conditional types, but haven't fully grasped them yet. ...

When using the listServiceLevelObjectives function, an UnhandledPromiseRejectionWarning occurs: The error message returned is "3 INVALID_ARGUMENT

Hey there, I'm struggling to retrieve a list of SLOs in my Google Cloud project via the REST API using TypeScript. Unfortunately, I keep running into an error message. Could you lend me a hand with this? The error reads: (node:47173) UnhandledPromis ...

In the function ngOnChange, the SimpleChange currentValue is supposed to be defined, but for some reason, the

Within the TypeScript code, a name variable is assigned input from another component. @Input() name : any ; In the ngOnChange function, I retrieve and print the SimpleChange object in the following manner. ngOnChanges(changes: SimpleChange){ console.l ...