作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我们的应用程序中有几条路线,用户不应通过直接在浏览器的地址栏中输入网址来导航这些路线。
相反,当我们使用 router.navigate()
通过我们的应用程序逻辑以编程方式导航时,我们只想让它们可访问。
使用 Angular 的 CanActivate
守卫,是否有一些标志或属性可以用来区分这两种情况:
当用户在地址栏中输入 /no/direct/access
时,直接访问路由
正在通过 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/
我是一名优秀的程序员,十分优秀!