【发布时间】:2020-04-21 12:34:06
【问题描述】:
我有一个位于路由器外部的导航组件,它使用一个可重用的图标组件,该组件依赖于绝对 url 指向 SVG 图标,该图标是通过组件内的 getter 检索的:
public get absUrl(): string {
return window.location.href.split('#')[0];
}
不幸的是,当从守卫触发时,重定向视图不会使用新的 abs url 更新。
我已经用 setTimeout 做了一个解决方法,但它超级 hacky - 它纯粹是为了证明最终导致问题的链中存在一些延迟,window.location.href 的值是正确的。
解决方法如下:
public absUrl = window.location.href.split('#')[0];
ngAfterViewInit() {
setTimeout(() => {
this.absUrl = window.location.href.split('#')[0];
this.ref.detectChanges();
}, 200);
}
- 仅当在受保护的路径上加载整个应用程序时,在加载应用程序后尝试随后访问受保护的路径才能正常工作。
- 当以不存在的路径加载整个应用程序并被重定向到 /404 时会发生这种情况
- 如果我设置 0 - 100ms 超时,它不会及时更新
- 通过router-outlet加载的组件正常工作,图标内的abs url更新准确。
有人对如何正确实施这个有任何想法吗?我的直觉是,如果您尝试加载受保护的路线,这与应用程序第一次加载的方式有关。
【问题讨论】:
-
为什么不能使用
router.url属性? -
@PierreDuc router.url 将比仅仅使用 window.location.href 更落后,即使在 window.location.href 工作的情况下,它也不会有更新的值来工作跨度>
标签: angular angular-router angular-changedetection virtual-dom