英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论