canActivate 防护仅在刷新后才起作用

Dat*_*dze 4 routes angular2-routing canactivate angular

我有 canActivate 守卫,它位于所有路线上(在父路线上)。当我第一次访问任何链接时它可以正常工作,但是当我更改路线时它不起作用。Guard 是关于登录用户的(如果 api 返回我已登录,则返回 true,否则我将其重定向到登录页面)我应该做什么?谢谢

Jea*_* A. 6

在您定义的同一守卫中,实现 CanActivateChild 接口,并调用相同的逻辑。在您的路由中,定义 CanActivate 和 CanActivateChild。

在你的守护下

@Injectable()
export class MyGuard implements CanActivate, CanActivateChild {

  constructor() {}

  canActivate() {
    // Your logic here to identify the value to return
  }

  canActivateChild() {
     return this.canActivate();
  }
}
Run Code Online (Sandbox Code Playgroud)

在你的路由中

let routes:Routes = [
 { 
   path: 'myPath', 
   canActivate: [ MyGuard ] 
   canActivateChild: [ MyGuard ],
   children: [
     { path: 'mychild1', .... },
     { path: 'mychild2', .... }
   ]
]
Run Code Online (Sandbox Code Playgroud)

阅读有关 angular.io 保护子路由的指南:https://angular.io/guide/router#canactivatechild-guarding-child-routes