Roh*_*han 6 angular2-routing angular
我知道我们可以使用在路由器路径中设置参数'/:id'.但我想创建一个不确定长度的数组,如下所示:'/:id1/:id2/:id3/...'
目前我正在管理最多三个这样的参数:
const routes: Routes = [
{ path: '/:name1', component: MyComponent, canActivate: [ LocalUserGuard ] },
{ path: '/:name1/:name2', component: MyComponent, canActivate: [ LocalUserGuard ] },
{ path: '/:name1/:name2/:name3', component: MyComponent, canActivate: [ LocalUserGuard ] }
Run Code Online (Sandbox Code Playgroud)
但是我想将它扩展到任意数量的参数.
小智 6
您可以使用 UrlMatcher来匹配您想要的任何类型的 Url。
function tagRoute(url: UrlSegment[]) {
if(url[0].path.match('tags-list'))
{
return ({consumed: url})
}else {
return null;
}
}
const appRoutes: Routes = [
{matcher: tagRoute, component: TagComponent },
{path:'**', component: HomeComponent}
];
Run Code Online (Sandbox Code Playgroud)
然后你可以使用TagComponent中的ActivatedRoute来获取 url 段,如上面提到的 @johnrsharpe 。
this.activateRoute.url.subscribe((segments: UrlSegment[]) => {
segments.shift();
segments.join('/');
});
Run Code Online (Sandbox Code Playgroud)
如果您希望它完全是任意的,您可以使用通配符路由:
const routes: Routes = [
{ path: '**', component: MyComponent, canActivate: [ LocalUserGuard ] },
]
Run Code Online (Sandbox Code Playgroud)
然后在里面MyComponent你可以通过以下方式访问URL段ActivatedRoute:
@Component({...})
export class MyComponent {
constructor(private route: ActivatedRoute) {
route.url.subscribe((segments: UrlSegment[]) => {
// do whatever you need to with the segments
});
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅示例Plunker:http://plnkr.co/edit/9YYMwO?p = preview