Angular路由参数问题



我有如下几个路由:我的主/基础应用程序路由如下所示:

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

PagesModule的Routing如下所示:

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

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

123作为:projectId和1作为:id,我想为ServingComponent和CompareComponent的URL是这样的:localhost: 4200/项目/123/服务/1localhost: 4200/项目/123/比较/1

哪些是有效的方式:通过HTML导航的工作方式如下:

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

问题:当我从TS文件中导航时,它不起作用。

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

你能告诉我哪里出了问题吗?我需要修改我的路线吗?我想知道为什么TS导航不工作,而导航工作从HTML。请建议。

如果你想使用相对路径,你需要像这样添加relativeTo属性:this.router.navigate(['../compare'], {relativeTo: this.activatedRoute});(同时添加model.id参数)

详细信息:https://angular.io/guide/router#specifying-a-relative-route