我正在尝试复制类似 Twitter 的 URL(即
@username
)。据我所知,我可以使用 matcher
而不是使用 path
来实现它。到目前为止一切正常,但遗憾的是我无法使用 matcher
访问我的子路线。它不是加载我定义的 component
,而是加载父组件。
我的代码: 应用程序路由.module.ts
const routes: Routes = [
{
path: '',
loadChildren: () => import('./home/home.module').then((m) => m.HomeModule),
},
{
matcher: (url: UrlSegment[], group: UrlSegmentGroup, route: Route) => {
if (!url || url.length === 0) {
return null;
}
const pattern = new RegExp(/^@[\w]+$/gm);
if (!pattern.test(url[0].path)) {
return null;
}
return {
consumed: url,
posParams: {
username: new UrlSegment(url[0].path.substr(1), {}),
},
};
},
loadChildren: () =>
import('./profile/profile.module').then((m) => m.ProfileModule),
},
{
path: 'post',
loadChildren: () => import('./post/post.module').then((m) => m.PostModule),
},
];
此路线可通过
/@johnsmith
到达。现在我用组件 info
定义了另一条名为
ProfileInfoComponent
的路线
配置文件路由.module.ts
const routes: Routes = [
{
path: '',
component: ProfileComponent,
children: [
{
path: 'info',
component: ProfileInfoComponent,
},
],
},
];
其他变化
const routes: Routes = [
{
path: '',
component: ProfileComponent,
},
{
path: 'info',
component: ProfileInfoComponent,
},
];
但是转到
/@johnsmith/info
会加载父组件 (ProfileComponent
) 而不是 ProfileInfoComponent
。有什么理由吗?
我通过将
consumed: url
更改为这个 consumed: url.length === 1 ? url : url.slice(0, 1),
让它以某种方式工作
很高兴看到它对你们中的一些人有所帮助。已经有一段时间了,我现在实际上已经转向 React / NextJS,但我想我可以解释一下发生了什么。
考虑这段代码:
const urlSegments = ['@johnsmith', 'info'];
const slicedUrl = urlSegments.slice(0, 1);
console.log('Segments:', urlSegments, 'Sliced URL Segment:', slicedUrl);
我们的路由器匹配器仅检查第一个匹配项 (
/@johnsmith
) 并忽略后续的每个段。然后,它通过延迟加载加载我们的 ProfileModule
和指定的 ProfileModuleRouter
。
不知何故,它无法将下一个 URL 段发送到我们的后续模块路由器,这就是为什么我们匹配
@johnsmith
并加载我们的 ProfileModule
,它加载 ProfileRoutingModule
并仅将 info
传递到 ProfileRoutingModule
路由器,其中包含参数 username
.
现在可能会有所不同,但这就是我所记得的。 :)