代码之家  ›  专栏  ›  技术社区  ›  Niladri Banerjee - Uttarpara

Angular 6如何实现canActivateChild

  •  1
  • Niladri Banerjee - Uttarpara  · 技术社区  · 6 年前

    我是个新手。我已经成功地集成了auth-guard,以便登录的用户可以访问私有页面。为此,我使用了 CanActivate . 现在,我打算使用另一种类型的保护,防止登录用户访问某些私有页面。 从…起 https://www.concretepage.com/angular-2/angular-2-4-route-guards-canactivate-and-canactivatechild-example canActivateChild 以达到类似的效果。

    app-routing.module.ts 我使用的文件如下:

    const routes: Routes = [ ...
    { path: 'myaccount', loadChildren: '../module/myaccount/myaccount.module#MyAccountModule',canActivate: [AuthGuard] },...];
    

    myaccount 组件,我还有其他几个子组件。

    myaccount-routing.module.ts ,我写道:

    const routes: Routes = [
    ...
    { path: 'abc', component: AbcComponent,
        children: [
        { path: 'xyz', component: XyzComponent, canActivateChild: [ AuthGuard ] },
    ... ]
       }
    ];
    

    abc abc-routing.module.ts

    const routes: Routes = [
    ...
    { path: 'xyz', component: XyzComponent, canActivateChild: [ AuthGuard ]},
    ...
    ];
    

    这是我的 auth.guard.ts :

    import { Injectable } from '@angular/core';
    import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild} from '@angular/router';
    import { CommonService } from './../services/common.service';
    
    @Injectable()
    export class AuthGuard implements CanActivate {
    
      private userData:any={};
    
        constructor(
            private router: Router,  
            private commService : CommonService
        ) { }
    
        canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        ...
        }
        canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
        console.log("fired!);
        return true;
        }
    }
    

    当我从浏览器转到xyz页面时,说 myaccount/abc/xyz ,它应该启动浏览器控制台,但是,我在浏览器控制台中看不到任何文本。CLI中也没有错误。我刷新了菜单 xyz 然而,佩奇运气不佳。浏览器控制台中没有文本。有什么想法吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   joaqcid    6 年前

    你在哪里提供服务 AuthGuard ?从示例中可以看出,它不是在根目录中提供的。你可以把它改成 @Injectable({providedIn:'root'})

    编辑

    stackblitz ,看起来像 canActivateChild 当它有父对象时触发 canActivate . 如果需要在特定页面上执行验证,则应添加另一个页面 激活 在您希望保护的页面上