如何在Angular路由中通过redirectTo获取url片段(锚点参数)



我正在尝试通过路由器表进行Angular路由重定向,想知道有没有简单的方法可以通过重定向获得url片段。我有这样的东西:

{
path: ':word',
redirectTo: 'blah/:word',
pathMatch: 'full'
}

当我使用参数localhost:4200/test#fragment运行此程序时,Angular将其重定向到localhost:4200/blah/test,而不使用fragment。我已经通过做一个解析器来绕过这个问题,在那里我用碎片重定向到正确的地方,但这感觉很愚蠢,因为我需要把我的虚拟组件放在路由器上,如下所示:

{
path: ':word',
resolve: { _: RedirectResolver },
component: DummyComponent, // We never go here
}

如果我省略了组件,那么Angular就不起作用了。有什么好的或土生土长的方法来完成这种行为吗?

您可以设置"preserveFragment";至true(文档:https://angular.io/api/router/NavigationExtras)

一种有助于保护的解决方案:

{
path: '/',
pathMatch: 'full',
component: Component, // Component from '@angular/core' as dummy component because we need something to put here (either component or redirectTo or loadChildren)
canActivate: [
(route: ActivatedRouteSnapshot): UrlTree => {
return inject(Router).createUrlTree(['redirect'], { fragment: route.fragment });
},
],
},

最新更新