Angular 4 get headers from an API response

I am sending an API request, it returns an array of data, but I don’t know how to extract the headers from this URL, this is what I 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 the answer, that in this case the resource

any idea?

+5
source share
5 answers

Headers are part of the response class , so you should see them in a handler, for example

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

When you execute .map(this.extractData) , the let body = res.json() from this.extractData retrieves everything from the response except body .

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

Here's a demo of Plunker .

+6
source

Clear angular 5 answer

By default, this.http.whatever the returned observable will be displayed in the data , not in the HttpResponse.

If you have a peak at: https://angular.io/api/common/http/HttpClient you will notice that the parameters accept a "watch" parameter of type HttpObserve. Although he did not document what HttpObserve is, if you put it as an “answer”, you will instead get an instance of HttpResponse<T> ( https://angular.io/api/common/http/HttpResponse )

So here is a sample request:

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

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

+2
source

A bit more exotic example in Angular 5 shown below. Using HttpClient to send to the GraphQL server, read the response, and then retrieve the response header value and the response body value. In this case, the header is Total-Count. cars is a field (an array of cars) under other field data in the body. Also shown is the use of the first rxjs operator instead of subscribing.

 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; }) } 
+1
source

Return type of the angular method Http.get returns the type of the response. This object has a header object that contains information about the headers. It also has a url property.

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

Source: https://habr.com/ru/post/1268408/


All Articles