Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何测试当前路线是否有防护?_Angular - Fatal编程技术网

Angular 如何测试当前路线是否有防护?

Angular 如何测试当前路线是否有防护?,angular,Angular,我用的是角度10 当用户单击注销按钮时,如果当前路由具有AuthGuard(我整个应用程序中唯一的防护),则我希望将用户重定向到主页 我的注销功能非常简单: logout() { this.authService.logout().subscribe() // TODO: redirect to the homepage if the current route is guarded } 注销功能与应用程序的标题一起存在,因此它出现在所有页面上 我将如何实现这一点 我的路线定义也很简单

我用的是角度10

当用户单击注销按钮时,如果当前路由具有AuthGuard(我整个应用程序中唯一的防护),则我希望将用户重定向到主页

我的注销功能非常简单:

logout() {
  this.authService.logout().subscribe()
  // TODO: redirect to the homepage if the current route is guarded
}
注销功能与应用程序的标题一起存在,因此它出现在所有页面上

我将如何实现这一点

我的路线定义也很简单,如下所示:

{
  path: 'saves',
  canActivate: [AuthGuard],
  loadChildren: () => import('./routes/saves/saves.module').then(m => m.SavesModule)
}
请注意,没有任何子路由是受保护的

短暂性脑缺血发作

我尝试了
this.route.routeConfig
但没有雪茄,它只是不断返回空值:

ngOnInit() {
  setInterval(() => {
    console.log(this.route.routeConfig)
  }, 1000)
}
然而,我很高兴使用
this.router.config
这样做:

import { find } from 'lodash-es'

logout() {
  this.authService.logout().subscribe() // this line has nothing to do with the solution, just added for completeness
  // redirect to home route if current route is guarded
  const parts = this.router.url.split('/')
  const routeName = parts.length > 1 ? parts[1] : null
  if (routeName) {
    const routeConfig = find(this.router.config, {path: routeName})
    const isGuarded = routeConfig && routeConfig.canActivate
    if (isGuarded) this.router.navigateByUrl('/home').then()
  }
}

如果注入并检查激活的路由,则它具有routeConfig属性。routeConfig属性包含基础路由信息,包括guard等。谢谢,根据您的评论,我提出了一个解决方案,我已经添加了该解决方案-但是,我不确定这是最佳解决方案,如果其他人提出了更简单的解决方案,我很乐意听到,而且+1您也很高兴听到。你的警卫叫你注销吗?警卫能否通过路由快照或与警卫类似的程序?可能路由快照或类似的快照包含该信息?如
import { find } from 'lodash-es'

logout() {
  this.authService.logout().subscribe() // this line has nothing to do with the solution, just added for completeness
  // redirect to home route if current route is guarded
  const parts = this.router.url.split('/')
  const routeName = parts.length > 1 ? parts[1] : null
  if (routeName) {
    const routeConfig = find(this.router.config, {path: routeName})
    const isGuarded = routeConfig && routeConfig.canActivate
    if (isGuarded) this.router.navigateByUrl('/home').then()
  }
}