使用拦截器进行身份验证时如何防止 Angular 显示路由

how to prevent Angular from showing route when using an interceptor for authentication

我在 Angular 6 中使用 http 拦截器来检查用户身份验证(JWT 等)。我的实现与此处描述的非常相似:

拦截器运行良好,我按预期进入了登录屏幕。问题是在拦截器重定向到登录屏幕之前,它非常短暂地闪烁了它正在保护的路由。换句话说,大约一毫秒,我试图保护的路由被显示,然后拦截器强制用户进入登录屏幕。

我不想显示受保护的路线,即使是一毫秒。我知道 "RouteGuard" 可能是解决方案,但我希望有更简单的方法,这将允许我使用拦截器保护所有路由,而无需在每条路由上指定路由保护。

const appRoutes: Routes = [
    {
        path: 'homepage',
        component: Home
    },
    {
        path: 'login',
        component: LoginComponent
    }
];

然后,在我的 auth.interceptor.ts 文件中(不使用整个文件,只使用相关部分)...

        return next.handle(request).do((event: HttpEvent<any>) => {
            if (event instanceof HttpResponse) {
                // we are ok to show the protected route!
            }
        }, 
        (err: any) => {
            if (err instanceof HttpErrorResponse) {
                if (err.status === 401) {
                    this.router.navigate(['/login']);
                }
            }
        });
        ...

我看到 "homepage" 路由的时间很短,然后我看到了登录屏幕。我根本不想看到主页路由,哪怕是一毫秒。

您可以使用 children 保护您的所有路线:

const appRoutes: Routes = [
    {
        path: 'login',
        component: LoginComponent
    },
    {
        path: '',
        canActivate: [AuthGuard],
        children: [
            {
                path: 'homepage',
                component: Home
            }
        ],
    }
];

您可以在 https://angular.io/guide/router#guard-the-admin-feature

阅读更多内容