【发布时间】:2019-03-20 05:50:24
【问题描述】:
我正在使用以下路由做一个 Angular 应用程序:
const routes: Routes = [
{
path: '',
component: LoginLayoutComponent,
children: [
{
path: '',
redirectTo: 'login',
pathMatch: 'full'
},
{
path: 'login',
component: LoginComponent
}
]
},
{
path: '',
component: HomeLayoutComponent,
canActivate: [AuthGuardService],
children: [
{
path: 'users',
component: UsersComponent,
},
{
path: 'detail/:id',
component: UserComponent,
},
{
path: 'dashboard',
component: DashboardComponent,
data: {
expectedRole: 'admin'
}
},
{
path: 'home',
loadChildren: './views/home/home.module#HomeModule',
data: {
preload: true,
delay: false
}
},
{
path: 'error',
component: ErrorComponent
},
]
},
];
如果我没有登录并且我请求任何安全 URL,例如 http://localhost:4200/users 或 http://localhost:4200/dashboard,那么会重定向到 http://localhost:4200/,并且应用程序会进入无限循环。如果我已登录,则可以正常工作。
浏览器控制台显示以下消息Navigation triggered outside Angular zone。
这是我的auth guard 服务:
canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
const expectedRole = route.data.expectedRole ? route.data.expectedRole : null;
const tokenPayload = this.tokenService.getDecodedAccessToken();
return this.authService.isAuthenticated()
.pipe(
map(isAuth => {
if (!isAuth) {
this.router.navigate(['login']);
return false;
} else {
return true;
}
}),
catchError((error, caught) => {
return of(false);
})
);
}
canLoad(): Observable<boolean> {
if (this.authService.isAuthenticated()) {
return of(true);
} else {
return of(false);
}
}
我在Angular 7
编辑:现在通过以下身份验证保护解决了该问题:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.authService.isAuthenticated()
.pipe(
map(isAuthenticated => {
if (!isAuthenticated) {
this.authService.setPostLoginRedirectUrl(state.url);
this.router.navigate(['login']);
return false;
} else {
return true;
}
}),
catchError((error, caught) => {
return of(false);
})
);
}
以及以下路线:
const routes: Routes = [
{
path: '',
component: LoginLayoutComponent,
children: [
{
path: '',
redirectTo: 'login',
pathMatch: 'full'
},
{
path: 'login',
component: LoginComponent
}
]
},
{
path: '',
component: HomeLayoutComponent,
canActivateChild: [AuthGuardService],
children: [
{
path: 'users',
component: UsersComponent,
},
{
path: 'detail/:id',
component: UserComponent,
},
{
path: 'dashboard',
component: DashboardComponent,
data: {
expectedRole: 'admin'
}
},
{
path: 'home',
loadChildren: './views/home/home.module#HomeModule',
data: {
preload: true,
delay: false
}
},
{
path: 'error',
component: ErrorComponent
},
]
},
];
【问题讨论】:
-
您的
LoginLayoutComponent和您的HomeLayoutComponent具有相同的路径:'' -
这是因为他们有子路由。有关示例,请参见 stackoverflow.com/a/46531192/958373。
-
我认为@user184994 是对的。即使它们有子路由,您也需要指定父路由的名称。
-
@Stephane 重定向到内部登录的目的是什么?另外,如果您没有登录并尝试访问不受保护的路径,会发生什么情况?
-
我解决了这个问题,但无法解释如何。
标签: angular