我正在用Angular 5.x SPA替换现有的AngularJS 1.6.x SPA,我想让我的用户对这个更改透明。
我担心对现有应用程序有书签的用户,因为它在URL中有哈希值(例如:example.com/#/menu
和example.com/#/item/37
);
但是,新应用程序在URL中没有哈希值(例如:example.com/menu
和example.com/item/37
)。
路径和路由都是相同的,除了当前应用程序中的#/
。
有没有办法可以配置Angular路由来删除#/
并使用新应用程序的无哈希路由配置?
我可以复制我的所有路由以适应有和没有哈希的路径,但必须有一种方法不需要加倍我的代码。
// Don't really want to do this:
const routes: Routes = [
{
path: 'menu',
component: MenuComponent
},
{
path: '#/menu',
component: MenuComponent
},
// etc.
];
同样,重定向每个#/
路径也会使代码加倍。
// Don't really want to do this:
const routes: Routes = [
{
path: 'menu',
component: MenuComponent
},
{
path: '#/menu',
redirectTo: 'menu'
},
// etc.
];
我希望这些方面有一些东西:
{
path: '#/*',
redirectTo: '*' // Somehow reference the wildcard part of the path here
}
提前感谢你的帮助。
@Yanis发布的答案几乎有效,但需要稍微调整一下。他的回答绝对值得赞成;但是,下面是我实施的工作解决方案:
export class AppComponent implements OnInit {
constructor (private router: Router) { }
ngOnInit() {
this.router.events.subscribe(event => {
if (event instanceof NavigationStart) {
if (!!event.url && event.url.match(/^\/#/)) {
this.router.navigate([event.url.replace('/#', '')]);
}
}
});
}
}
我不知道这是否正确。但你可以这样做:目标是订阅NavigationChange,然后检查你当前的路线是否以'#!'开头,如果是,你重定向到正确的路线。
class AppComponent implement OnInit {
constructor(router: Router) {
//When url change, we check if actual url have #! on it, then we redirect to the route without it.
router.events.subscribe((event: NavigationEvent): void => {
this.url = router.url;
if (this.url.match('/^#!/')) {
this.router.navigate(
this.url.replace('#!','')
);
}
}
);
}
}
在我看来,另一个更复杂的问题是使用自定义“匹配器”。更多信息: