基于字符串第一个字符的Angular 9路由



在我的Angular 9应用程序中,当路径以"&";。

例如";mywebsite.com/@sample用户"应该导航到用户组件;mywebsite.com/@sample-user/:post-id";到UserPostView组件;mywebsite.com/sample用户";(路径开头没有@(应该导航到另一个组件。

const routes: Routes = [{path: '@:username', component: UserComponent}, {path: '@:username/:pist-id', component: UserPostViewComponent}, {path: 'sample-user', component: InternalComponent}]

我该怎么做?

我认为您可以使用带有regex的自定义匹配器。

RouterModule.forRoot([
{
matcher: (url) => {
if (url.length === 1 && url[0].path.match(/^@[w]+$/gm)) {
return {
consumed: url,
posParams: {
username: new UrlSegment(url[0].path.substr(1), {})
}
};
}
return null;
},
component: ProfileComponent
}
])

看看这篇文章,它有所有的答案。

https://medium.com/@brancontroberts/customizedroute-matching-with-the-angular-router-fbdd48654883

最新更新