Search code examples
angularangular2-servicesangular2-http

Angular 2 - Get Headers From Http Requests


All my Backend API requests return new token information in headers, even when them throw exceptions. In the next request I need to send these new token information.

So I'm trying to figure out an unique and standard way to do that, so I'm trying:

let requestOptions = new RequestOptions(Object.assign({
      method: method,
      url: environment.apiHost + url,
      body: body,
      headers: authenticatedRequest ? this.requestService.getAuthHeaders() : this.requestService.getJsonHeaders(),
      withCredentials: authenticatedRequest
    }));

this.http.request(new Request(requestOptions))
        .map((res:Response) => { this.storageService.setAuthInfo(res.headers); res.json() } )
        .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

The problem I'm facing with is that when I subscribe to this method, res variable is returning undefined.

What do you suggest me?


Solution

  • The problem is you have to return a response res.json() explicitly from your map function as you used {}.

    this.http.request(new Request(requestOptions))
       .map((res:Response) => { 
           this.storageService.setAuthInfo(res.headers); 
           return res.json();
       } )
       .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
    

    Similar answer here