问题
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