Re Initaite the last failed request after refresh

2019-08-21 04:01发布

问题:

I have my angular 4 application which sends multiple request at the same time one after another to the API which is protected by OAuth2, I m facing issue when the request fails with 401 status code,I need to generate a new access token and re initiate the same request to the API and return the response to the method which is waiting for it. 1- All the request fails one after another - so in order to hold other request to proceed i have added a loop which holds the request coming to the server when the token generation is in progress 2- To initiate the request I added the line next.handle(request) again in the block but was not working, then i tried calling this.intercept(request,next) method even then it was not working, after that the last approach i added was to re handle the request in the error block so now the code of the intercept method looks as below, but then i realized that the request is not even processed further even if i retry to handle the request. There are several tutorial simply suggesting next.handle(request), but in my case it does not works as expected.
Only I was successful in handling the requests which comes after the failed request because till then the new access token is generated but the request which was failed simply drops.

Please see the code flow in the link!

I have already spent a lot of time on debugging

回答1:

I was able to achieve this with by adding Observable.fromPromise in the intercept method and then calling a method that returns promise and the method was recursively called until I get the refresh token, but adding a delay in between every call so that I don't end up calling recursively several times.

Please refer this link for the my code. Please comment if facing any issues .

Reference : https://www.illucit.com/en/angular/angular-5-httpinterceptor-add-bearer-token-to-httpclient-requests/