首页 > 解决方案 > 在父页面与子组件之间传递参数

问题描述

我在使用 Angular 9 中的路由机制时遇到了困难。我有一个 Buildings 组件和一个 BuildingDetailComponent。我无法在 BuildingDetailCompoent 中获取参数。即使它出现在地址栏中的 URL 中,它也不在那里。

所以在父组件中我只有这个..

const routes: Routes = [ { path: '', component: BuildingsComponent, data: { title: 'Buildings' } } ];

然后在路由的建筑细节组件中我有这个。

 const routes: Routes = [ { path: '', component: BuildingDetailComponent, data: { title: 'Buildings},
  children: [ 
    { path: 'building-detail', component: BuildingDetailComponent, data: { title: 'Building Detail' } },
    { path: 'building-detail/:id', component: BuildingDetailComponent, data: { title: 'Building Detail' } }       
  ]
}
];

所以基本上我在我的 BuildingComponent.html 中像这样传递值......

<td style="text-align: center;"><button [routerLink]="['./building-detail', building.ID]" class="button button-primary"><span >Edit</span></button></td>

然后在 BuildingDetailComponent 中,我使用以下命令收集值...

this.buildingID = (this.route.snapshot.paramMap.get('id') != null) ? parseInt(this.route.snapshot.paramMap.get('id')) : 0;

我已经尝试了很多路由,最后这是我现在需要的唯一部分 this.building.ID 是未定义的,所以当我查看 this.route 时,即使在地址栏中可以看到传递的值,也没有参数。

我可以通过执行以下操作来解决它,并且可能会用它做一些事情,但感觉不对。

let URL = this.router.url;

我希望作为最后的途径,有人可以就此向我提供建议。

谢谢。

标签: angulartypescriptangular-activatedroute

解决方案


问题是 Angular 将转到第一个匹配的路线,这就是path: ''为什么你看不到:id那里。

我们可以通过进行一些更改来改进子路由,因此 Angular 将进入子路由中的:id路径

const routes: Routes = [ 
  { 
    path: 'building-detail',   
    children: [ 
      { path: '', component: BuildingDetailComponent, data: { title: 'Building Detail' } },
      { path: ':id', component: BuildingDetailComponent, data: { title: 'Building Detail' } }       
    ] 
  }
];

希望能帮助到你


推荐阅读