Angular 4 get headers from API response

后端 未结 5 1277
我在风中等你
我在风中等你 2020-12-06 05:50

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

<         


        
相关标签:
5条回答
  • 2020-12-06 05:57

    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; 
      })
    }
    
    0 讨论(0)
  • 2020-12-06 06:02

    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.

    0 讨论(0)
  • 2020-12-06 06:06

    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
      });
    
    0 讨论(0)
  • 2020-12-06 06:19

    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));
    
    0 讨论(0)
  • 2020-12-06 06:24

    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.

    0 讨论(0)
提交回复
热议问题