Angular 4 CanActivateChild不起作用

时间:2017-06-07 22:17:00

标签: angular angular-router-guards

我正在尝试使用CanActivateChild限制对我的路由系统的访问,但是当我尝试阻止用户导航到一组子状态时,RouteGuard不起作用,仅在CanActivate上。这是我的路由模块:

export const routes = [
    { path: "", redirectTo: "/signin", pathMatch: "full" },
    { path: "signin", component: SigninComponent },
    {
        path: "user",
        component: UserComponente,
        canActivate: [AuthGuard],
        canActivateChild: [AuthGuard],
        children: [
            { path: "profile", component: ProfileComponent, },
            { path: "address", component: AddressComponent, },
        ]
    },
    { path: "test", component: TestComponent, canActivate: [AuthGuard] },
];

在此示例中,如果我尝试访问路由test,我可以看到正在执行的AuthGuard,调用函数canActivate

但是当我尝试导航到任何子路线(个人资料或地址)时,没有任何反应。 canActivate上都没有调用canActivateChildAuthGuard

这是我的警卫档案:

import { Injectable } from '@angular/core';
import { CanActivate, CanActivateChild } from '@angular/router';
import { getString } from 'application-settings';
import { AppConfig } from './../config';

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
    constructor() { }

    canActivate() {
        console.log('canActivate executing.');

        if (!getString(AppConfig.authToken)) {
            alert('You need to be logged in.');
            return false;
        }
        return true;
    }

    canActivateChild() {
        console.log('canActivateChild executing.');
        return this.canActivate();
    }
}

1 个答案:

答案 0 :(得分:0)

您需要在构造函数中注入路由器,也需要将其导入。

import { Router } from '@angular/router'

constructor(
    private router: Router
  ) {}

因为您需要让路由器知道更改。您可以返回boolean,observable或UrlTree,以便路由器可以更新其状态。