0

我正在尝试使用 限制对我的路线系统的访问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并且canActivateChild不会在AuthGuard.

这是我的保护文件:

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();
    }
}
4

1 回答 1

0

您需要在构造函数中注入路由器,还需要导入它。

import { Router } from '@angular/router'

constructor(
    private router: Router
  ) {}

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

于 2018-12-04T14:37:17.627 回答