Angular 2 - Get headers from Http requests

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

So, I'm trying to find a unique and standard way to do this, 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 that I am facing is that when I get subscribeto this method, the variable resreturns undefined.

What do you offer me?

+4
source share
1 answer

The problem is that you must explicitly return the response res.json()from your function mapas 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'));

+3

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


All Articles