javascript - Angular:无法使用 UrlMatcher 导航到子路由
问题描述
前言:我的部分 URL 策略有一个可选参数。这意味着,URL 路径可以以区域代码和语言代码或仅以语言代码开头。这些代码然后由实际的应用程序路由处理。
/us/eng --> Home page
/us/eng/about-us --> About Us page
/eng/about-us --> About Us page
我正在尝试使用 UrlMatcher 来完成 URL 中的可选区域代码。
我的问题是,主页总是显示。它从不显示“关于我们”页面或任何其他子路径。
部分 app.routes.ts
export function baseRouteMatcher(url: UrlSegment[]) {
const posParams: { [key: string]: UrlSegment } = {};
const consumed: UrlSegment[] = url;
if (url[0].path.length === 2 && url[1].path.length === 3) {
posParams.region = url[0];
posParams.lang = url[1];
} else if(url[0].path.length === 3) {
posParams.region = new UrlSegment('world', {});
posParams.lang = url[0];
}
return ({consumed, posParams});
}
export const appRoute = {
name: 'app',
matcher: baseRouteMatcher,
children: [
{ path: 'terms-of-service', component: ContentComponent },
{ path: 'privacy-policy', component: ContentComponent },
{ path: 'about-us', loadChildren: './about-us/about-us.module#AboutUsModule' },
{ path: '', component: HomeComponent },
]
};
我很可能完全误解了 UrlMatcher 的功能。很难找到复杂的例子。任何帮助表示赞赏!
解决方案
这是真的。我不明白 UrlMatcher 是如何工作的。发生了两件事:
- 每次运行匹配器函数时,我都会使用部分 url(而不是在不需要时返回 null)。
- 每次运行匹配器功能时,我都会消耗所有段,而不仅仅是我需要的部分。这导致
HomeComponent
每次都得到。
这是工作代码:
export function baseRouteMatcher(segments) {
// If we don't have any segments
if (!segments[0]) {
return null;
}
// If we only have a language, consume just the first segment
// Else if we have a region and a language, consume first two segments
if (segments[0].path.length === 3) {
return { consumed: segments.slice(0, 1), posParams: { region: 'world', lang: segments[0].path } };
} else if (segments[0].path.length === 2 && segments[1].path.length === 3) {
return { consumed: segments.slice(0, 2), posParams: { region: segments[0].path, lang: segments[1].path } };
}
// The segments don't contain a region or language, don't consume anything
return null;
}
推荐阅读
- python - python Turtle.update() 中的蛇游戏导致问题
- python - 将 Ray 与 PyTorch 一起使用时,无法将配置中的多个值参数传递给我的模型
- jdbc - 有没有办法我们可以使用 JDBC-Odbc 桥通过 SQLDeveloper 或 toad 或任何其他基于 java 的应用程序连接到 oracle
- javascript - POST http://localhost:3001/[object%20Promise] 404 (Not Found) React Axios
- java - Spring-boot 重定向:/ 到 http 而不是 https
- typescript - 如何从每个类型都有一个 id 的联合中获取类型
- javascript - 在 javascript 中“constructor --> prototype”链永无止境
- api - 使用 POSTMAN 客户端时出现错误“无法向 localhost 发送请求”
- tensorflow - 更改 TF 对象检测 API 的模型架构
- reactjs - 在 Next JS 中实现加载更多按钮