Angular 5导航被Guard取消

时间:2018-05-01 21:49:37

标签: angular routing

我的路由配置如下所述。

const PUBLIC_ROUTES: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'session-transfer/:id', component: SessionTransferComponent }
];

const SECURE_ROUTES: Routes = [
{ path: 'clients', component: ClientSelectionComponent },
{ path: 'app/:application', component: SessionTransferComponent },
{ path: 'applications', component: AppSelectionComponent },
{ path: '', redirectTo: 'clients', pathMatch: 'full' }
];

const routes: Routes = [
{ path: 'st/:transferId',canActivate: [AuthGuard], canActivateChild: [AuthGuard], children: SECURE_ROUTES },
{ path: '', redirectTo: '/login', pathMatch: 'full', },
{ path: '', component: PublicComponent, children: PUBLIC_ROUTES },
{ path: '', component: SecureComponent, canActivate: [AuthGuard], canActivateChild: [AuthGuard], children: SECURE_ROUTES }
];

@NgModule({
imports: [RouterModule.forRoot(routes, { useHash: true })],
exports: [RouterModule]
})

以下是我的示例AuthGuard代码

_canActivate() {
  return true;
}

canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | 
boolean {

return this._canActivate();
}

canActivateChild(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | 
boolean {
     return this._canActivate();
}

当我导航到路线st/:transferId/app/:application时,导航取消。在跟踪日志中,GuardCheckEnd ShouldActivate返回true。即使这样,nvigation也会取消并重定向到/login路由。

任何人都可以帮忙。感谢

1 个答案:

答案 0 :(得分:0)

我相信你的错误的原因在于:

        const routes: Routes = [
    { path: 'st/:transferId',canActivate: [AuthGuard], canActivateChild: [AuthGuard],children: SECURE_ROUTES }, 
    { path: '', redirectTo: '/login', pathMatch: 'full', }, { path: '', component: PublicComponent, children: PUBLIC_ROUTES }, 
    { path: '', component: SecureComponent, canActivate: [AuthGuard], canActivateChild: [AuthGuard], children: SECURE_ROUTES } ]; 

Angular根据排列顺序使用路线。在您的情况下,您有三条路径到同一路径。因此,angular将使用Routes数组中与路径匹配的第一个路由,即登录。

我的建议是

  1. 让守卫管理重定向登录。例如,在AuthGuard服务中,

    if(!this._activate){
         this.router.navigate(['/login'])}
    else{
        return this._activate
     }
    
  2. 为公共路由和安全路由提供唯一路径而不是空字符串,最后从路由中删除redirectTo登录。