繁体   English   中英

角度:使用UrlMatcher无法导航到子路线

[英]Angular: Can't navigate to children routes with 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是如何工作的。 发生了两件事:

  1. 每次运行matcher函数时,我都会消耗一部分url(这与不需要时返回null相对)。
  2. 每次运行matcher函数时,我也消耗了所有段,而不仅仅是我需要的部分。 这导致每次都获得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;
}

您可以为不同的路径制作两个不同的匹配器

{matcher:languageMatcher,component:AboutUs},
{matcher:homePageMatcher,component:HomePage},

有关更多信息,您可以阅读以下博客: https : //medium.com/@lenseg1/loading-different-angular-modules-or-components-on-routes-with-same-path-2bb9ba4b6566

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM