具有段通配符的角度路由

时间:2018-05-07 22:02:04

标签: angular

我正在为Angular 6应用设置路由,我希望有一条路径可以匹配可变数量的段。目前我有一个如下所示的路由配置:

const routes: Routes = [
  { path: '', redirectTo: '/catalog', pathMatch: 'full' },
  { path: 'login', component: LoginFormComponent },
  { path: 'catalog', component: CatalogComponent, canActivate: [SessionGuard] },
  { path: 'repo/:name', component: RepositoryComponent, canActivate: [SessionGuard] }
];

匹配repo/test之类的网址并将其发送到RepositoryComponent,但repo/foo/bar会引发错误:

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'repo/foo/bar'
Error: Cannot match any routes. URL Segment: 'repo/foo/bar'
    at ApplyRedirects.push../node_modules/@angular/router/fesm5/router.js.ApplyRedirects.noMatchError (router.js:1341)

我已经习惯了ASP.NET MVC中的约定,它允许我声明这样的路由:

[HttpGet("repo/{*name}")]

哪个匹配repo/testrepo/foo/bar,并将第一个斜杠(testfoo/bar)后的所有内容放在name参数中。有没有办法通过Angular获得等效行为?

1 个答案:

答案 0 :(得分:0)

显然没有内置方法可以做到这一点。我最终得到的是这样的路由设置:

const routes: Routes = [
  { path: '', redirectTo: '/catalog', pathMatch: 'full' },
  { path: 'login', component: LoginFormComponent },
  { path: 'catalog', component: CatalogComponent, canActivate: [SessionGuard] },
  { path: 'repo', component: RepositoryComponent, canActivate: [SessionGuard], children: [{
    path: '**', component: RepositoryComponent
  }] }
];

处理请求路由,但不处理参数评估。要获得与**通配符匹配的细分,我需要在Router上注入的RepositoryComponent对象中进行搜索:

getRepo(): void {
  this.Name = this.route.snapshot.children[0].url.join('/');
}