【问题标题】:Angular 6 How to implement canActivateChildAngular 6 如何实现 canActivateChild
【发布时间】:2019-02-08 21:34:04
【问题描述】:

我是 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 ] },
... ]
   }
];

在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;
    }
}

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

【问题讨论】:

  • 我投票决定将此问题作为题外话结束,因为我知道“CanActivateChild”不能用于单个子路由/路径。它将保护路径下的所有子路径。

标签: angular angular-guards


【解决方案1】:

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

编辑

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

【讨论】:

  • 感谢您的回复。我在auth.guard.ts 中使用了您的代码,但是它不起作用。我的问题是如何通过 canActivateChild 防止单个子项。请参阅 myaccount-routing.module.ts 文件。在 myaccount 路径下,有几个孩子,但我想通过 canActivateChild 阻止一个路径说 xyz。
猜你喜欢
  • 2019-05-10
  • 1970-01-01
  • 2019-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多