【问题标题】:angular router URL always points to home on initial load角度路由器 URL 在初始加载时始终指向主页
【发布时间】:2021-05-08 10:03:33
【问题描述】:

在初始加载 Angular 应用时,router.url 始终指向主页 URL ('/')。 即使我使用域/某些路由打开应用程序,路由 url 也是'/'。

代码如下:

构造函数(私有路由器:路由器){}

ngOnInit() {
  console.log(this.router.url);
  setTimeout(() => {
    console.log(this.router.url);
  }, 100);
}

超时(100 毫秒)后,URL 正确。

StackBlitz example

在预览时将其加载为初始路径:https://angular-epv4wn.stackblitz.io/home 并检查控制台。

SetTimeout 是解决方法,但我不想依赖它。

【问题讨论】:

  • NavigationEnd 你需要像在这个演示中一样检测这个事件stackblitz.com/edit/angular-ime53m?file=src/app/…
  • 这可行,但它适用于每次路线更改。我只需要初始加载 url。
  • 在 pipe() 中过滤后使用 take(1)。它会在第一次发出后自动取消订阅 observable

标签: angular angular-router


【解决方案1】:

路由器有很多事件,NavigationStart, GuardsCheck, RoutesRecognized, ResolveRoute... 您对 NavigationEnd 感兴趣,因为如果它存在于路由器或后备路径中,它将给出正确的路径

所以你需要等待导航完成...

 this.router.events
      .pipe(
        filter(event => event instanceof NavigationEnd)
      )
      .subscribe(url=> {
        console.log(this.router.url)
        console.log(event.url);
      });

两个控制台都会给你 /home

【讨论】:

  • 这可行,但它适用于每次路线更改。我只需要初始加载 url。
  • 在管道上添加 take(1) 在您不再需要时手动取消订阅
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-09
  • 1970-01-01
相关资源
最近更新 更多