我正在尝试使用 Angular 9 和我的
应用程序路由.module.ts
const routes: Routes = [
{
path: '', canActivate:[GuestGuard], component: BlankComponent, children:[
{path:'', loadChildren: () => import('./user/user.module').then(m => m.UserModule)}
],
},
{
path: '', canActivate:[AuthGuard], component: UserComponent, children: [
{path: 'dashboard', component: DashboardComponent},
{path:'', children:[
{path: 'roles', loadChildren: () => import('./roles/roles.module').then(m => m.RolesModule), },
}
]
},
{ path: '**', redirectTo: '', pathMatch: 'full' },
];
客人守卫.ts
用于屏蔽已经登录的用户
export class GuestGuard implements CanActivate, CanLoad {
constructor(private auth:Auth, private router:Router){}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const userLoggedIn = this.auth.isLoggedIn();
if(userLoggedIn){
this.router.navigateByUrl('dashboard');
return false;
}
return true;
}
canLoad(
route: Route,
segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {
const userLoggedIn = this.auth.isLoggedIn();
if(userLoggedIn){
this.router.navigateByUrl('dashboard');
return false;
}
return true;
}
}
auth-guard.ts
允许访问已登录的用户(与访客相反)
export class AuthGuard implements CanActivate, CanLoad {
constructor(private auth:Auth, private router:Router){}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const userLoggedIn = this.auth.isLoggedIn();
if(!userLoggedIn){
this.router.navigateByUrl('/');
return false;
}
return true;
}
canLoad(
route: Route,
segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {
const userLoggedIn = this.auth.isLoggedIn();
if(!userLoggedIn){
this.router.navigateByUrl('/');
return false;
}
return true;
}
}
上面的代码按预期工作正常。但是当我在来宾路径上使用 canLoad 时,我得到了
Throttling navigation to prevent the browser from hanging. See <URL>.
登录用户路径,不执行canLoad函数(使用console.log测试)
什么时候应该使用 canLoad?