我是个新手。我已经成功地集成了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
然而,佩奇运气不佳。浏览器控制台中没有文本。有什么想法吗?