Angular Prevent Multiple Token Refresh On Asynchronous Requests
All my http requests go through the custom HttpService. This service refreshes the token when it's expired before sending the request. It works fine but it refreshes the token mult
Solution 1:
You can create your own Promise when you call updateToken()
like this :
@Injectable()
export class HttpService extends Http {
private updateTokenPromise: Promise<any>;
constructor (backend: XHRBackend, options: RequestOptions) {
.............
}
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
................
if(tokenNotExpired('access_token')){ // if token is NOT expired
return super.request(url, options);
} else { // if token is expired
// There is already a call to updateToken() in progress,
// wait for it to finish then process the request
if (this.updateTokenPromise) {
return this.updateTokenPromise.then(() => {
return this.request(url, options);
});
}
// Start to call updateToken(), then resolve the promise
else {
this.updateTokenPromise = new Promise((resolve, reject) => {
this.updateToken()
.then((result: boolean) => {
resolve(result);
});
});
return this.updateTokenPromise.then(() => {
return this.request(url, options);
});
}
}
}
updateToken(): Observable<boolean> {
// set the new token
.....
}
}
This way you won't have multiple parallel calls of updateToken()
Post a Comment for "Angular Prevent Multiple Token Refresh On Asynchronous Requests"