Search code examples
httpgetangularwp-api

headers response in http.get


I spent hours trying to figure out how to get headers response like x-total-objects and status code after http.get request, I have this class service, and I need to access those attributes to paginate my results

in service:

@Injectable()
export class WPCollections{

  constructor(private http: Http){  }

  fetch(url){
     let headers = new Headers({ 'Content-Type': 'application/json' });
     let options = new RequestOptions({ headers: headers });

     return this.http.get(url, options).map(res => res.json());
  }
}

in component:

@Input() args;
posts = new Array<any>();
service: Observable<any>;

constructor(private wp: WPCollections) { }

fetchData(args){
   this.service = this.wp.fetch(args);
   this.service.subscribe( 
     collection=>{
         this.posts = collection;
     },
     err => this.onError(err)

   );
}

Solution

  • In fact in your case you need to return the response object itself and not only the payload.

    For this you to remove the map operator:

      fetch(url){
         let headers = new Headers({ 'Content-Type': 'application/json' });
         let options = new RequestOptions({ headers: headers });
    
         return this.http.get(url, options);
      }
    }
    

    And in your component:

    @Input() args;
    posts = new Array<any>();
    service: Observable<any>;
    
    constructor(private wp: WPCollections) { }
    
    fetchData(args){
       this.service = this.wp.fetch(args);
       this.service.subscribe( 
         response=>{
             this.posts = response.json();
           var headers = response.headers;
         },
         err => this.onError(err)
    
       );
    }