问题
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