angular - 相对于 Angular 中的子模块导航

标签 angular angular2-routing

我有一些具有不同 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/

相关文章:

angular2 路由类型错误 : Cannot read property 'forRoot'

angular - 使用路由器的 "redirectTo"中的函数来确定重定向到哪里可以防止 aot

css - 如何以 2/4 Angular 为动画状态赋予类名?

javascript - 更新数据时绘制动画绘图旭日图

angular - 为什么 templateUrl 不起作用?

javascript - 如何以 Angular react 形式迭代 FormGroup 中的 FormArray

javascript - AngularFireMessaging - 错误 this._next 不是函数

angularjs - 如何在 angular2 中添加过滤器?

html - 如何修复底部的按钮并滚动剩余内容

javascript - angular4 或 javascript 中的 Json 网络 token 生成