【问题标题】:Why does route guard canLoad not fire, but canActivate does为什么路由保护 canLoad 不会触发,但 canActivate 会
【发布时间】:2017-02-21 23:53:57
【问题描述】:

我有一个 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 Providers 中,如下所示:

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

导航正常工作,每当我尝试导航到 shiftmanage 路径时,都会触发 canActivate 路由保护。

问题: canLoad 路由守卫永远不会被击中。

问题:

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

【问题讨论】:

    标签: angular typescript angular2-routing


    【解决方案1】:

    canLoad用于加载lazy-loaded modulesloadChildren

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

    【讨论】:

    • 好的,在仔细阅读链接的文档之后,这是有道理的,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多