I tried to implement the interceptor concept in my angular demo project but I'm getting error on httpInterceptor line 7 i.e
`export const httpInterceptor: HttpInterceptorFn = (req, next) => {`
I'm new to angular, I started learning angular through YouTube, angular official website. I'm doing a Todo Management App project by watching a YouTube video. I encountered an error while practising the interceptor code, but the same code is working on the YouTube video. In the YouTube video, they are using Angular version 16 and now I'm using Angular version 17 and I done change the code according.
import { HttpErrorResponse, HttpHandler, HttpInterceptorFn, HttpRequest } from '@angular/common/http';
import { inject } from '@angular/core';
import { TokenService } from '../services/token.service';
import { Router } from '@angular/router';
import { catchError, throwError } from 'rxjs';
export const httpInterceptor: HttpInterceptorFn = (req, next) => {
const tokenService = inject(TokenService);
const router = inject(Router);
tokenService.isAuthenticated.subscribe({
next: (value) => {
if (value) {
req = req.clone({
setHeaders: {
Authorization: `Bearer ${tokenService.getToken()}`,
},
});
}
},
});
return next(req).pipe(
catchError((e: HttpErrorResponse) => {
if (e.status === 401) {
tokenService.removeToken();
return router.navigate(['']);
}
const error = e.error?.error?.message || e.statusText;
return throwError(() => error);
})
);
}
This is the error message I'm getting:
Type '(req: HttpRequest<unknown>, next: HttpHandlerFn) => Observable<boolean | HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<...> | HttpUserEvent<...>>' is not assignable to type 'HttpInterceptorFn'.
Type 'Observable<boolean | HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<unknown> | HttpUserEvent<unknown>>' is not assignable to type 'Observable<HttpEvent<unknown>>'.
Type 'boolean | HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<unknown> | HttpUserEvent<unknown>' is not assignable to type 'HttpEvent<unknown>'.
Type 'boolean' is not assignable to type 'HttpEvent<unknown>'.
The problem seems to come from returning the router.navigate()
function when using the pipe
operator :
router.navigate
returns a boolean
which changes the return type of the observable
which you can't do as the HttpInterceptorFn
as a precise return type.
This is fixable by just calling router.navigate
instead of returning its return value.
We can then return EMPTY
to end the stream and complete the observable :
import {
//...
EMPTY,
//...
} from 'rxjs';
return next(req).pipe(
catchError((e: HttpErrorResponse) => {
if (e.status === 401) {
tokenService.removeToken();
router.navigate(['']);
return EMPTY;
}
const error = e.error?.error?.message || e.statusText;
return throwError(() => error);
})
);