Angular 4 CanActivateChild doesn't work

痞子三分冷 提交于 2019-12-24 07:25:31

问题


I'm trying to restrict access to my route system using CanActivateChild, however when I try to prevent user's navigation to a set of child states, the RouteGuard doesn't work, only on CanActivate. This is my routing module:

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

In this example, if I try to access the route test, I can see the AuthGuard being executed, the function canActivate is called.

But when I try to navigate to any of the children routes (profile or address), nothing happens. Both, canActivate and canActivateChild doesn't get called on the AuthGuard.

This is my guard file:

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:


you need to Inject the Router in you constructor, also you need to import it.

import { Router } from '@angular/router'

constructor(
    private router: Router
  ) {}

Because you need to let the Router know of the changes. You can return boolean, observable or UrlTree, so the router can update its state.



来源:https://stackoverflow.com/questions/44423662/angular-4-canactivatechild-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!