gpt4 book ai didi

angular - 为什么路由守卫 canLoad 不开火,但 canActivate 开火

转载 作者:太空狗 更新时间:2023-10-29 17:16:33 26 4
gpt4 key购买 nike

我有一个 Angular 2.0.1(最终版)应用,它使用 HashLocationStrategy 作为路线导航策略。

我定义了一条路线如下:

    { 
path: 'shiftmanage', component: ShiftManageComponent,
canLoad: [AuthGuard],
canActivate: [AuthGuard]
},

这是 AuthGuard 类:

    import { Injectable }           from '@angular/core';
import {
Route,
Router,
CanLoad,
CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot } from '@angular/router';

@Injectable()
export class AuthGuard implements CanLoad, CanActivate {
constructor(private router: Router) {
console.log("AuthGuard constructor")
}

canLoad(route: Route): boolean {
if (route.path === "shifts") {
return true;
} else {
return false;
}
}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (route.routeConfig.path === "shiftmanage") {
return true;
} else {
return false;
}
}
}

然后我将这个保护类添加到 NgModule Provider 中,如下所示:

providers: [
AuthGuard,
{ provide: LocationStrategy, useClass: HashLocationStrategy }
... other providers
]

导航正常,每当我尝试导航到 shiftmanage 路径时,canActivate 路由守卫就会被触发。

问题 canLoad 路由守卫从未被击中。

问题:

这个 canLoad 守卫是否因为 HashLocationStrategy 而没有被击中,还是我做错了什么?

最佳答案

canLoad用于加载lazy-loaded modules使用 loadChildren

{
path: 'child',
canLoad: [AuthGuard],
loadChildren: 'path/to/child.module'
}

关于angular - 为什么路由守卫 canLoad 不开火,但 canActivate 开火,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40011143/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com