Angular 2 is an Http request method that is called both with success and with errors

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:

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))
    .catch((error:any) => this.storageService.setAuthInfo(res.headers));

Now I have to set a new token in the map and catch methods. Is there a method called both for success and for errors, when I could set new token information ( this.storageService.setAuthInfo(res.headers))?

0
source share
1 answer

.finally , finally, response. map , headers . finally this.storageService.setAuthInfo.

myRequest(){
    let header;
    this.http.request(new Request(requestOptions))
        .map((res:Response) => { 
           //take headers to pass it when request succeed/fails
           header = res.headers;
           return res.json();
        )
        .finally(() => this.storageService.setAuthInfo(headers))
}
0

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


All Articles