Home > Back-end >  How to get response headers using angular HttpClient
How to get response headers using angular HttpClient

Time:04-21

Here I am using rxjs Ajax to make a post api call and take filename from response headers and download file. I need to replace Ajax call with angulars http service. I am not getting how to replace this with http as there is no xhr in https response that i am getting. Need help in converting this ajax call to http call. Thanks :)

ajax({
      url: url,
      method: method,
      responseType: "blob",
      headers: headers,
      body: body,
    }).subscribe((data) => {
      let filename = "";
      let disposition = data.xhr.getResponseHeader("Content-Disposition");
      if (disposition && disposition.indexOf("attachment") !== -1) {
        let filenameRegex =
          /filename\*?=['"]?(?:UTF-\d['"]*)?([^;\r\n"']*)['"]?;?/;
        let matches = filenameRegex.exec(disposition);
        if (matches != null && matches[1]) {
          filename = decodeURIComponent(matches[1]);
        }
      }
      let blob = new Blob([data.response]);
      let link = document.createElement("a");
      link.href = window.URL.createObjectURL(blob);
      link.download = filename;
      link.click();
    });
  }

CodePudding user response:

http
  .get<any>('url', {observe: 'response'})
  .subscribe(resp => {
    console.log(resp.headers.get('X-Token'));
  });

from this answer: Read response headers from API response - Angular 5 TypeScript

  • Related