Ben*_*ikt 7 angular2-routing angular
我有一些具有不同 url 前缀的嵌套模块。现在我想在不指定前缀的情况下在一个模块中导航(在我的模块中,我不想知道在哪个前缀下可以访问该模块)。
这些是我的 app.module 的路由:
const APP_ROUTES: Routes = [
{
path: '',
children: [
{ path: '', component: MainComponent },
{ path: 'nested', loadChildren: 'app/nested/nested.module#NestedModule' }
]
}
];
export const routing = RouterModule.forRoot(APP_ROUTES, { useHash: true });
Run Code Online (Sandbox Code Playgroud)
这些是我的nested.module 的路由:
const APP_ROUTES: Routes = [
{
path: '',
component: NestedComponent,
children: [
{ path: '', component: NestedSubComponent },
{ path: 'sub', component: NestedSubComponent },
{ path: 'sub/:id', component: NestedSubComponent }
]
}
];
export const routing = RouterModule.forChild(APP_ROUTES);
Run Code Online (Sandbox Code Playgroud)
例如,现在我想从 /#/nested/sub 导航到 /#/nested/sub/123。我怎样才能做到这一点?我不知道我在我的子模块中嵌套了多深(即,如果我的子路由是 / 或 /sub 或 /sub/:id),而且我不想使用嵌套前缀,因为我想要一个通用的解决方案,可以也可用于其他子模块。
您可以使用Router.navigate()方法的第二个参数来指定relativeTo选项,然后它将相对于该路线导航。
constructor(private router: Router,
private activatedRoute: ActivatedRoute) {}
goDeeper() {
this.router.navigate(['next-nested-route'], {relativeTo: this.activatedRoute});
}
goBack() {
this.router.navigate(['../'], {relativeTo: this.activatedRoute});
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用隐式设置的routerLink指令,ActivatedRoute只是不要将第一个斜杠放在那里。
<a routerLink="/next">absolute</a>
<a routerLink="next">relative next</a>
<a routerLink="..">relative back</a>
Run Code Online (Sandbox Code Playgroud)
更多关于这个角度文档:https : //angular.io/guide/router#!# relative- navigation
| 归档时间: |
|
| 查看次数: |
3210 次 |
| 最近记录: |