I am having issues with my Angular 6 Interceptor. I have migrated the code from Angular 5.x to 6.0. and rxjs 5.x to 6.x. When I try to create a new user account, the request seems to be called twice. I know this because I log the error to the console. I have noticed that I get this duplication when I try to get the Id token from firebase auth, See code snippet below.
intercept (request: HttpRequest<any>, next: HttpHandler): observable<HttpEvent<any>> {
return this.auth.getIdToken().pipe(
mergeMap((token: any) => {
if (token) {
request = request.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
}
return next.handle(request).pipe(
tap((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
}
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
if ((err.status === 401) || (err.status === 403)) {
this.router.navigate([WellknownRoutesConstants.SIGN_IN], { queryParams: { returnUrl: this.router.routerState.snapshot.url }});
}
}
})
);
}));
}
getIdToken (): Observable<any> {
return ngFireAuth.authState.pipe(
tap((user) => {
if (user) {
return observableOf(user.getIdToken());
} else {
return observableOf;
}
}),
catchError(observableOf)
);
}
Grant's answer is good, but there is a problem.
If the user logs out, the auth.idToken
Observable emits a value because the token value changes to null
. The request object remains unchanged (but still initialised), and so the HTTP request is repeated.
I used take(1)
to take only the first value emitted by the auth.idToken
Observable. I also changed to switchMap
(see take):
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.auth.idToken.pipe(
take(1), // <-------------- Only emit the first value!
switchMap((token: any) => {
if (token) {
request = request.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
}
return next.handle(request);
})
);
}
This works for me since upgrading to Angular 6 / RxJS 6. Here's my interceptor:
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(
private auth: AngularFireAuth
) {
console.log('token interceptor constructor');
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.auth.idToken.pipe(
mergeMap((token: any) => {
console.log(token);
if (token) {
request = request.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
}
return next.handle(request);
}));
}
}
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