繁体   English   中英

Angular 4 CanActivateChild不起作用

[英]Angular 4 CanActivateChild doesn't work

我正在尝试使用CanActivateChild限制对我的路由系统的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 ,我可以看到正在执行的canActivate ,调用函数canActivate

但是当我尝试导航到任何子路线(配置文件或地址)时,没有任何反应。 canActivatecanActivateChild都不会在AuthGuardAuthGuard

这是我的警卫档案:

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

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

import { Router } from '@angular/router'

constructor(
    private router: Router
  ) {}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM