gpt4 book ai didi

javascript - Angular 防护 : Prevent manually accessing a URL

转载 作者:行者123 更新时间:2023-11-29 15:07:15 24 4
gpt4 key购买 nike

我们的应用程序中有几条路线,用户不应通过直接在浏览器的地址栏中输入网址来导航这些路线。

相反,当我们使用 router.navigate() 通过我们的应用程序逻辑以编程方式导航时,我们只想让它们可访问。

使用 Angular 的 CanActivate 守卫,是否有一些标志或属性可以用来区分这两种情况:

  1. 当用户在地址栏中输入 /no/direct/access 时,直接访问路由

  2. 正在通过 router.navigate(['/', 'no', 'direct', 'access']) 访问路由(这可能反过来由不同的守卫,所以 router.navigated 不幸的是似乎在这里没有帮助)

最佳答案

我没有发现区分您描述的案例的可能性。我找到了一种方法来防止手动导航到路由

您可以检查路由器上的 .navigated 属性。根据文档,它是

True if at least one navigation event has occurred, false otherwise

export class PreventDirectNavigationGuard implements CanActivate {
constructor(
private _router: Router,
) { }
canActivate(
_activatedRouteSnapshot: ActivatedRouteSnapshot,
_routerStateSnapshot: RouterStateSnapshot,
): boolean | UrlTree {

return this._router.navigated;
}
}

Angular 也有导航触发标志。来自 source code

Identifies how this navigation was triggered.

imperative - Triggered by `router.navigateByUrl` or `router.navigate`.
popstate - Triggered by a popstate event.
hashchange - Triggered by a hashchange event.
       trigger: 'imperative' | 'popstate' | 'hashchange';

关于javascript - Angular 防护 : Prevent manually accessing a URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58767490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com