【问题标题】:Access ParamMap访问参数映射
【发布时间】:2020-03-25 09:41:28
【问题描述】:

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

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');
}

我该怎么做?

【问题讨论】:

  • 你在这得到什么,你有没有尝试 console.log?
  • 我不确定你的问题是否正确。参考上面列出的我的路由结构,我在 OdlMainComponent 和每个子路由中得到了这个。在每种情况下,记录 this._odlId 都会让我得到 0。记录每个 paramMaps 显示它是空的

标签: angular parameters routes router


【解决方案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'];
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 2021-04-18
    • 2021-04-28
    • 1970-01-01
    • 2022-08-17
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多