我正在为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/test
和repo/foo/bar
,并将第一个斜杠(test
或foo/bar
)后的所有内容放在name
参数中。有没有办法通过Angular获得等效行为?
答案 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('/');
}