首页 > 解决方案 > 角度路由参数问题

问题描述

我有几条如下所示的路线。我的主要/基本应用程序路由如下所示:

const routes: Routes = [{
    path: 'projects',
    loadChildren: () => import('../app/pages/pages.module').then(m => m.PagesModule)
}]

PagesModule 的路由如下所示:

const routes: Routes = [
    {
        path: ':projectId/model', component: ModelComponent
    },
    {
        path: ':projectId/compare/:id', component: CompareComponent
    }
    {
        path: ':projectId/serving/:id', component: ServingComponent
    }
]

对于模型组件,url 是正确的,即:localhost:4200/projects/123/model

使用 123 作为 :projectId 和 1 作为 :id,我希望 ServingComponent 和 CompareComponent 的 URL 类似于:localhost:4200/projects/123/serving/1 localhost:4200/projects/123/compare/1

工作原理:通过 HTML 导航的工作原理如下:

 <button [routerLink]="['../compare', model.id]">Compare</button>

问题:当我从 TS 文件导航时,它不起作用。尝试以下:

 this.router.navigate(['../compare', model.id]);

你能建议什么可能是错的吗?我需要修改我的路线吗?我想知道为什么 TS 导航不起作用,而导航从 HTML 起作用。请指教。

标签: angularangular8angular-componentsangular-router

解决方案


如果要使用相对路径,则需要添加relativeTo如下属性:( this.router.navigate(['../compare'], {relativeTo: this.activatedRoute}); 还添加model.id参数)

更多细节:https ://angular.io/guide/router#specifying-a-relative-route


推荐阅读