angular router 默认策略是先加载 component,然后更新 path,由于实际应用中在监听 NavigationStart 事件的回调函数中切换了 tab,采用默认策略会造成 tab 切换过来了,对应的 url 却没更新,请问如何将 router 设置首先更新 url path?
this._router.events.subscribe((ev) => {
if (ev instanceof NavigationStart) {
debounceTime(50);
this.setActiveTab(ev.url);
this.spinnerService.toggle(true).then();
}
});
根据这个问题,问了 DeepSeek:"how to set angular router to update path first",DeepSeek 给出了漂亮的回答,尤其是推理过程,通过推理过程可以学到更多东西
DeepSeek 给出的第1个解决方法:
- Update Your Router Configuration
Set urlUpdateStrategy: 'eager' in the router configuration:
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; const routes: Routes = [ // Your route definitions ]; @NgModule({ imports: [ RouterModule.forRoot(routes, { urlUpdateStrategy: 'eager', // Update URL immediately on navigation trigger }), ], exports: [RouterModule], }) export class AppRoutingModule {}
提供的示例代码有些滞后,用的还是 NgModule,基于 standalone mode 的配置代码如下:
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(
routes,
withRouterConfig({
urlUpdateStrategy: 'eager'
})
)
]
}
DeepSeek 也给出了采用这个方法需要考虑的问题:
- Important Considerations
- Guards/Resolvers: If a guard (e.g., canActivate) blocks navigation, the URL might change but the component won’t load, causing inconsistency.
- User Experience: Use this only if you’re certain navigation won’t be canceled unexpectedly, or handle such cases in your app.
DeepSeek 给出的第2个解决方法:
Alternative: Manually Update the URL (Advanced)
this.router.navigate(['/new-route'], { skipLocationChange: true }) .then(success => { if (success) { // Manually update the URL window.history.pushState({}, '', '/new-route'); } });
保险起见,采用了第2个解决方法,在切换 tab 后调用 window.history.pushState
修改 url
async ngOnInit() {
this._router.events.subscribe((ev) => {
if (ev instanceof NavigationStart) {
debounceTime(50);
this.setActiveTab(ev.url);
window.history.pushState({}, '', ev.url);
this.spinnerService.toggle(true).then();
}
}
}