1

我是 Angular 身份验证守卫的新手。我已经成功集成了 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组件中,myaccount我在以下内容中编写了以下内容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页面,没有运气。浏览器控制台中没有文本。任何想法?

4

1 回答 1

1

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

编辑

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

于 2019-02-08T12:58:02.630 回答