Angular6 如何实现canActivateChild

Angular 6 How to implement canActivateChild

我是 Angular auth guard 的新手。我已成功集成 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 ] },
... ]
   }
];

myaccount 下的 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;
    }
}

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

你在哪里提供 AuthGuard?,从示例中它没有在根目录中提供。您可以将其更改为 @Injectable({providedIn:'root'})

编辑

看看这个 stackblitz,它看起来像 canActivateChild 在它有一个父 canActivate 时被触发。如果您需要在特定页面上执行验证,您应该在您希望保护的页面上添加另一个 canActivate