Angular 2 - Http request method which is called on both success and error cases

时间秒杀一切 提交于 2019-12-12 02:46:39

问题


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:

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));

For now I have to set new token in map and catch methods. Is there a method which is called both on success and error cases where I could set new token info (this.storageService.setAuthInfo(res.headers)) ?


回答1:


You could use .finally over observable, but by using finally function you are not going to get control over response stuff. So better have map function on observable & from there take headers information to some variable. Then pass on that from finally's this.storageService.setAuthInfo method call.

Code

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))
}


来源:https://stackoverflow.com/questions/40769737/angular-2-http-request-method-which-is-called-on-both-success-and-error-cases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!