router.navigate()会立即改变路由器的URL吗?

huangapple go评论123阅读模式
英文:

Will router.navigate() change router url instantaniously

问题

我正在尝试查看navigate函数在执行后是否会更改路由器的URL。

this.router.navigate(['/home/products']);
if (this.router.url.includes('/home/products'))
console.log('changed');

英文:

I am trying to see if navigate function will change the router url right after executing.

this.router.navigate(['/home/products']);
if (this.router.url.includes('/home/products'))
  console.log('changed');

答案1

得分: 1

I change my comment to answer so I can format code in my response to your question.

它是异步的,默认情况下,在导航发生之前它不会等待所有其他代码执行完成。

但是,如果你想在路由后尝试执行你的代码,请尝试使用 async / await:

async yourFunction() {
  await this.router.navigate(['/home/products']);
  // 导航完成后执行的代码
}

或者使用 then:

this.router.navigate(['/home/products'])
  .then(() => {
    // 导航完成后执行的代码
  });

这样做会等待导航完成,然后执行后续的代码。

英文:

I change my comment to answer so I can format code in my response to your question.

It´s asynchronous, and by default, it does not wait for all other code executions to complete before the navigation takes place.

But if you want to try to execute your code after the route try async / await

async yourFunction() {
  await this.router.navigate(['/home/products']);
  // Code to execute after navigation is complete
}

or then

this.router.navigate(['/home/products'])
  .then(() => {
    // Code to execute after navigation is complete
  });

Like this it will wait till navigation is completed and execute the code after that.

huangapple
  • 本文由 发表于 2023年6月13日 18:44:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76464074.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定