Currently, I am encountering the following situation:
I have developed an authentication service using Angular/Fire with Firebase authentication. The authentication service is expected to return the ID token through the idToken observable from Angular/Fire:
public getAuthenticationToken(): Observable<string | null> {
const auth = getAuth()
return idToken(auth).pipe(
switchMap(token => {
return of(token)
})
)}
The HTTP Interceptor needs to extract the token from the authentication service and add it to the header if it exists:
@Injectable()
export class AuthenticationInterceptor implements HttpInterceptor {
constructor(private userService: UserService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.userService.getAuthenticationToken().pipe(
switchMap((token) => {
const newRequest = request.clone()
if(token) {
newRequest.headers.set('Authorization', token);
}
return next.handle(newRequest)
})
)
}
}
However, I am facing an issue where every request is sent out successfully the first time but fails to send subsequent requests. These requests are initiated by a feature service within an effect. Interestingly, removing the interceptor resolves the issue, allowing multiple requests to be sent as expected.
Here is an example effect:
SaveArticle$ = createEffect(() =>
this.actions$.pipe(
ofType(savedArticlesActions.saveArticle),
concatMap((payload) =>
this.articleService.saveArticle(payload).pipe(
map((response) =>
savedArticlesActions.saveArticleSuccess({
article: response.article, message: "Article successfully saved"
})
),
catchError((error) => of(savedArticlesActions.saveArticleFailure(error)))
)
)
)
);
When I changed the map operator to switchMap in the above effect, the requests were sent multiple times along with the interceptor. However, reverting to another map operator still resulted in each request being sent only once.
My current setup includes:
- Angular 16
- RXJS 7.5
I acknowledge that there may be a crucial aspect I am overlooking, but I am unsure of what it could be.
Thank you for any assistance provided.