Router.navigate() 在功能拦截器内不起作用

问题描述 投票:0回答:1

这是一个 Angular 功能拦截器,旨在管理应用程序使用期间可能出现的会话超时。

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);
            })
        );
};

但是,我遇到了注释行

router.navigateByUrl("/login")
的问题。每当执行此行时,都会出现错误,指出:“无法匹配任何路由。URL 段:'登录'。”

“登录”路线确实在应用程序中定义。

最初,我怀疑上下文有问题。但是,在检查代码后,我确认路由器已正确定义,并且我正在使用箭头函数,这应该保留上下文。

angular rxjs angular-router angular-httpclient-interceptors
1个回答
1
投票

您的代码也可以工作。您是否已在独立组件中导入路由器,如下所示:

注意: 您可以导入 RouterLink、RouterLinkActive 等。您不需要导入完整的

RouterModule
,但可以。

  imports: [CommonModule, RouterModule, MytestComponent],

MytestComponent是在路由中注册的组件:

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

这也很重要。将路线、所有导入和拦截器添加到您的应用程序中。

最后但并非最不重要的一点:

    <router-outlet></router-outlet>

router-outlet
在你的html部分很重要。有了这一切,您的应用程序就可以运行了。

© www.soinside.com 2019 - 2024. All rights reserved.