【问题标题】:Angular Guards: Prevent to manually access an URL but authorize refreshAngular Guards:防止手动访问 URL 但授权刷新
【发布时间】:2021-10-20 06:54:17
【问题描述】:

我创建了一个防止用户手动访问 URL 的 Guard,它工作正常。

问题是当我刷新页面时,Guard 会重定向我。

代码如下:

export class NavigationGuard implements CanActivate {

  constructor(private router: Router) { }

  canActivate(): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (this.router.navigated) {
      return true
    } else {
      this.router.navigate(['/'])
      return false
    }
  }
  
}

我已经看到我可以使用以下代码来获取刷新事件,但它基本上与 this.router.navigated 相反,所以它不起作用。

this.subscription = router.events.subscribe((event) => {
        if (event instanceof NavigationStart) {
          browserRefresh = !router.navigated;
        }
    });

这两种行为是否可能在我的 Guard 中同时起作用?

【问题讨论】:

  • 在“刷新”时,this.router.navigated 将是错误的,因为您没有通过路由器导航到任何地方。如果您不希望这将您重定向到“/”,则需要在 if 中关闭 this.router.navigated 以外的其他内容。

标签: angular typescript angular-routing angular-router-guards


【解决方案1】:

也许您可以结合this.router.navigated 使用“此页面是否刷新”的逻辑来检查该页面是否可以在角度应用程序中访问。

类似这样的:

    const pageAccessedByReload = (
      (window.performance.navigation && window.performance.navigation.type === 1) ||
        window.performance
          .getEntriesByType('navigation')
          .map((nav: any) => nav.type)
          .includes('reload')
    );
    return this.router.navigated || pageAccessedByReload

【讨论】:

  • 在 Angular 中使用 window.performance 是否安全?
  • 我不完全确定,但也许你只能使用performance.getEntriesByType("navigation")
猜你喜欢
  • 2020-03-05
  • 1970-01-01
  • 2017-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-03
  • 1970-01-01
  • 2020-07-31
相关资源
最近更新 更多