I have an interceptor in my Angular 7 app that makes a request to get the token before re-issuing the request. If multiple requests come in at once then they will all make a request to get the token. To avoid that I share an observable so that the result for getting the token is shared and that only one request is made to get the token.
I create the shared observable as follows
this.authService.sharedToken = this.authService.getToken().pipe(share());
Then I make the request
return auth.sharedToken.flatMap((res) => {
auth.saveTokenToLocalStorage(res);
return this.getRequestWithAuthentication(request, next, auth);
}).catch(function (err) {// I handle errors here
}
The problem is that flatMap is deprecated and replacing it with mergeMap won't work either. It seems mergeMap is a standalone function right now. So how can I get the code above to work.
I am using rxjs 6.4.0 and Angular 7.2.4
Thanks.
EDIT:
using the new pipe approach I have the following:
return auth.sharedToken.pipe(
mergeMap((res) => {
auth.saveTokenToLocalStorage(res);
return this.getRequestWithAuthentication(request, next, auth);
}), catchError(function (err) {
console.log("failed to get token")
return EMPTY;
}));
I cannot get the "failed to get token" to print when the request fails. I do more error handling there, so I need some code to be triggered when the request fails.
With RxJS 5.5 the new pipe operator syntax was introduced. In RxJS 6.0 it became mandatory to use over the old syntax. So you will have to replace your code by
.pipe(
mergeMap(...)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With