Angular2 路由器:匹配任何 url,包括子目录

Angular2 router: matching any url, including subdirectories

我正在使用 Angular2 更新旧网站,其中一个先决条件是所有 URL 仍必须匹配。

这是开发的最初阶段,我正在研究路由器。

到目前为止,我必须创建一个主页、一个产品页面和一个错误页面。

产品页面的 "old" 链接如下所示: /category/subcategory/some/eventual/other/things/productName-id.html

我已经复制了 Matan Shukry's Complex Url Matcher,这是我当前的代码:

import { ComplexUrlMatcher } from '../../functions/complex.url.matcher';

const appRoutes: Routes = [
    {
        path:      '',
        component: HomepageComponent,
    },
    {
        matcher:   ComplexUrlMatcher('product', /.*/), // very permissive regex here, in order to test
        component: ProductComponent,
    },
    {
        path:      '**',
        component: Error404Component,
    },
];

我目前的问题是我可以匹配任何东西,前提是我的 url 没有任何斜线。

如何使这些 url 与它们的完整路径(包括所有斜杠?)相匹配。

最好在 angular 中使用 parameters 您可以为路由定义参数

{ path: 'hero/:a/:b/:c/:d/:e/:f/:g', component: HeroDetailComponent },
{ path: 'hero/:a/:b/:c/:d/:e/:f', component: HeroDetailComponent },
{ path: 'hero/:a/:b/:c/:d/:e', component: HeroDetailComponent },
{ path: 'hero/:a/:b/:c/:d', component: HeroDetailComponent },
{ path: 'hero/:a/:b/:c', component: HeroDetailComponent },
{ path: 'hero/:a/:b', component: HeroDetailComponent },
{ path: 'hero/:a', component: HeroDetailComponent },
{ path: 'hero', component: HeroDetailComponent },

然后订阅paramMap

HeroDetailComponent 

import { ActivatedRoute } from '@angular/router';

constructor(
    private route: ActivatedRoute
) { }

this.route.paramMap.subscribe(params => {
  console.log(params);
});

您将获取订阅中的所有参数并进行操作

这里id是一个参数。同样的方式你可以将多个参数传递给你的路线 创建您的路线结构

https://angular.io/guide/router#route-parameters-required-or-optional 转到此 link 了解更多详细信息

anein's function 的帮助下,我终于找到了方法(谢谢,伙计!)。

Matan Shukry 的方法对我的需要来说过于复杂。

这是我的要点:https://gist.github.com/MarcBrillault/87f8df9610cfa3ed112afc3f8da474e8

编辑:要点已更新。