2

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

4

1 回答 1

4

在您定义的同一个守卫中,实现 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();
  }
}

在您的路由中

let routes:Routes = [
 { 
   path: 'myPath', 
   canActivate: [ MyGuard ] 
   canActivateChild: [ MyGuard ],
   children: [
     { path: 'mychild1', .... },
     { path: 'mychild2', .... }
   ]
]

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

于 2017-08-04T09:01:54.517 回答