I'm trying to replicate this behaviour on my project, but when I call return next(req) from the subscribe of the refresh token request, it doesn't "retry" the original request. How can I trigger a "retry" the original request with updated token?
Hey there! It sounds like you're working on implementing a token refresh mechanism in Angular. When you're trying to "retry" the original request after refreshing the token, you need to ensure that the new token is set in the headers of the original request before resending it. Here’s a quick approach: - Capture the Original Request: Before making the refresh token call, store the original request. - Refresh the Token: As you're already doing, refresh the token when needed. - Update the Original Request: Once you have the new token, update the original request’s headers with the new token. - Resend the Request: Finally, resend the original request with the updated token. It's a bit more complex than can be explained in a short comment, but this should give you a direction. If you'd like a detailed tutorial on this, let me know, and we might cover it in an upcoming video. Don’t forget to like, subscribe, and hit the bell icon for more updates! 🔔✨
@@AyyazTech Yes, you're right. I'm trying to implement a token refresh. My approach is, when the response of any request results in a 401 status code, I need to call my authService.refreshToken, which will return an HttpClient observable with token information. When it returns, I update my token on localStorage, then retry the original request. But when I call next(req) from inside the .subscribe() method of authService.refreshToken, it doesn't run. Checking the DevTools Network tab, I can see that Angular runs the main request, receives a 401 error, refreshes the token and stuck there.
That is probably beacuse u are using SSR in your project. In order to acces localstorage wrap it with the built in isPlatformBrowser() method. Check Angular docs.