Access ParamMap

问题描述 投票:0回答:1

似乎我不知道如何在我的路线中访问参数,我也不知道为什么。我具有以下路线结构:

const routes: Routes = [
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: 'foo',
    component: MainComponent,
    children: [
      // some sibling paths
      {
        path: 'odl/:id',
        component: OdlMainComponent,
        children: [
          {
            path: 'details',
            component: OdlDetailComponent
          },
          {
            path: 'phases',
            component: OdlPhasesComponent
          }
        ]
      }
    ]
  }
];
@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class ViewsRoutingModule {}

现在,我在OdlMainComponent中,好像无法在该路线中获取该ID。我尝试了以下解决方案,但均未成功:

constructor(
    private _route: ActivatedRoute
) { }

ngOnInit() {
    this._odlId = +this._route.snapshot.paramMap.get('id');
    // or
    this._odlId = +this._route.parent.snapshot.paramMap.get('id');
    // or
    this._odlId = +this._route.root.snapshot.paramMap.get('id');
}

我该怎么做?

angular parameters routes router
1个回答
1
投票

尝试做这样的事情:

看看代码:

_params: object;

constructor(
    private _route: ActivatedRoute
) { 
    this._route.params.subscribe(params => this._params = params);
    // console.log(this._params['id']);
}

ngOnInit() {
    this._odlId = + this._params['id'];
}

我希望您会发现这很有用,这就是我的方法。也许有人有比这更好的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.