首页 > 解决方案 > 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 的功能。很难找到复杂的例子。任何帮助表示赞赏!

标签: javascriptangulartypescript

解决方案


这是真的。我不明白 UrlMatcher 是如何工作的。发生了两件事:

  1. 每次运行匹配器函数时,我都会使用部分 url(而不是在不需要时返回 null)。
  2. 每次运行匹配器功能时,我都会消耗所有段,而不仅仅是我需要的部分。这导致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;
}

推荐阅读