【发布时间】:2019-11-22 05:17:38
【问题描述】:
我正在使用 http 拦截器来检查 Angular 6 中的用户身份验证(JWT 等)。我的实现与此处描述的非常相似:
Angular HTTP Interceptors - Redirect to Login page and skip further code execution
拦截器运行良好,我的登录屏幕如期而至。问题是在拦截器重定向到登录屏幕之前,它会非常短暂地闪现它正在保护的路由。换句话说,大约一毫秒,我试图保护的路由被显示出来,然后拦截器强制用户进入登录屏幕。
我不想显示受保护的路线,即使是一毫秒。我知道“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']);
}
}
});
...
发生的情况是我在很短的时间内看到了“主页”路线,然后我看到了登录屏幕。我根本不想看到主页路由,哪怕只有一毫秒。
【问题讨论】:
-
使用 Guard 来保护主页路由。 medium.com/@ryanchenkie_40935/…
标签: angular angular2-routing angular-http-interceptors