Angular 4 get headers from API response

I'm sending a request to an API, it returns an array of data, but I don't know how to extract the headers from that url, this is what i've tried in my service

@Injectable()
export class ResourcesService {
private resourcesurl = "http://localhost:9111/v1/resources";

constructor(private http: Http) { }

getResources() {
  let headers = new Headers();
  headers.append("api_key", "123456");
  return this.http.get(this.resourcesurl, { headers: headers 
 }).map(this.extractData).catch(this.handleError);
}
getresourceheaders(){
  let headers = new Headers();
  headers.append("api_key", "123456");
  let options = new RequestOptions();
  let testsss = options.headers
  let headerapi = this.http.request(this.resourcesurl, options);
  let test = this.http.get(this.resourcesurl, { headers: headers });
  console.log(headerapi);
}
private extractData(res: Response) {
  let body = res.json();
  return body.data || {};
}
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
  const body = error.json() || '';
  const err = body.error || JSON.stringify(body);
  errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
  errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
 }
}

I want to get the headers from that response that in this case is resourceurl

any idea?

Answers:

Answer

The headers are part of the Response class, so you should be able to see them in a handler like

http.get('/path/to/resource')
  .subscribe((res:Response) => {
    console.log(res.headers);
    // you can assign the value to any variable here
  });
Answer

Clear angular 5 answer

By default, this.http.whatever's returned observable will be on the data returned, not the HttpResponse.

If you have a peak at: https://angular.io/api/common/http/HttpClient You'll notice the options take an "observe" parameter of a HttpObserve type. While it's not documented what the HttpObserve is, if you put it as "response" then you will instead receive an instance of HttpResponse<T>(https://angular.io/api/common/http/HttpResponse)

So, here's an example request:

this.http.get(url, {observe: 'response'})
    .subscribe(resp => console.log(resp.headers))

Note: Due to browser cors security, you will not be-able to see headers unless the API provides Access-Control-Expose-Headers: with your custom headers if your api and angular app do not have the same domain.

Answer

When you do .map(this.extractData) the let body = res.json() from this.extractData function takes out everything from the response except the body.

Instead if you do following, .map((res: Response) => res), that will return the whole response and you can access all the attributes and assign them to variables.

Here's a Plunker demo.

Answer

A bit more of an exotic example in Angular 5 shown below. Using HttpClient to post to a GraphQL server, read the response and then extract a response header value and a response body value. The header is Total-Count in this case. cars is a field (array of Car) under another field data in the body. Also shows use of the rxjs first operator.

import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import { first } from 'rxjs/operators/first'; 
import { Car, CarPage } from '../models/car';  
..........
..........

public find(filter: string, sort: string, limit: number): Observable<CarPage> {
  let headers = new HttpHeaders().set("Content-Type", "application/graphql");
  let carPage: CarPage = { cars: [], totalCount: 0 };
  return this.http.post<HttpResponse<any>>('/graphql',
    `query cars { cars(filter: "${filter}", sort: "${sort}", limit: ${limit}) {
          id
          make
          model
          year 
        }
      }`,
      { headers: headers, observe: "response" }
  )
  .first((_, index) => index === 0, (response: HttpResponse<any>) => {
    let totalCountHeaderValues = response.headers.getAll("Total-Count");
    carPage.totalCount = (totalCountHeaderValues.length > 0) ? parseInt(totalCountHeaderValues[0]) : 0;  
    carPage.cars = response.body.data.cars; 
    return carPage; 
  })
}
Answer

The return type of the angular Http.get method returns a Response type. This object has a headers object that contains information about the headers. It also has a url property.

this.http.get(url).map(resp => console.log(resp));

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.