Search code examples
angularrxjsangular-routerangular-httpclient-interceptors

Router.navigate() not working inside functional interceptor


This is an Angular functional interceptor created to manage possible session timeouts during application usage.

export const sessionExpiredInterceptor: HttpInterceptorFn = (req, next) => {
    const router: Router = inject(Router);
    return next(req)
        .pipe(
            catchError((error: HttpErrorResponse): Observable<never> => {
                if (error.status == 401 && !req.url.includes("login")) {
                    // router.navigateByUrl("/login");
                    window.location.href = '/login';
                }
                return throwError(() => error);
            })
        );
};

However, I'm facing an issue with the commented-out line router.navigateByUrl("/login"). Whenever this line is executed, an error occurs stating: "Cannot match any routes. URL Segment: 'login'."

The 'login' route is indeed defined in the application.

Initially, I suspected a context problem. However, after inspecting the code, I confirmed that the router is correctly defined, and I'm using arrow functions, which should preserve the context.


Solution

  • Your code works as well. Do you have imported the Router in your standalone component like this as example:

    Note: You can import RouterLink, RouterLinkActive and so on.. You don't need to import the complete RouterModule, but you can.

      imports: [CommonModule, RouterModule, MytestComponent],
    

    MytestComponent is the component which is registered in the routes:

    bootstrapApplication(App,{
      providers: [provideHttpClient(  withInterceptors([sessionExpiredInterceptor])),
      provideRouter([{path: "", pathMatch: "full", component: App}, {path: "test", pathMatch: "full", component: MytestComponent}])]});
    

    Thats important, too. Add the routes, all imports and your interceptor into your app.

    Last but not least:

        <router-outlet></router-outlet>
    

    router-outlet is important in your html part. With all this Your app will working.