我有一些具有不同 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 });
这些是我的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);
现在我想例如从/#/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});
}
您也可以使用
routerLink
指令,它有 ActivatedRoute
隐式设置,只是不要放第一个斜线。<a routerLink="/next">absolute</a>
<a routerLink="next">relative next</a>
<a routerLink="..">relative back</a>
更多关于这个的 Angular 文档:https://angular.io/guide/router#!#relative-navigation
关于angular - 相对于 Angular 中的子模块导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46833891/