代码之家  ›  专栏  ›  技术社区  ›  Tobias Gassmann

角度布线参数不可访问

  •  1
  • Tobias Gassmann  · 技术社区  · 6 年前

    编辑: (解决方案)

    原件 (问题):

    this.activatedRoute.params.subscribe((values) => {
      console.log('these are my parameters: ', values);
    });
    

    一切正常,我得到路线的参数没有任何问题。

    这是路由的工作配置:

    {
      path: 'details/:itemId',
      component: ItemDetailsComponent,
    },
    

    现在来谈谈这个问题: 当我试图简化我的路由(因为我不需要任何其他路由)时,会出现以下问题:对路由配置进行以下简单更改后,我无法再访问路由参数(它们是空的)。

    这是路由的缺陷配置:

    {
      path: ':itemId',
      component: ItemDetailsComponent,
    },
    

    3 回复  |  直到 6 年前
        1
  •  2
  •   SiddAjmera    6 年前

    看起来你还在尝试导航到 details/:itemId 当你本该这么做的时候 :itemId . 确保你导航到正确的路径。

    你换完衣服之后, /details 将起作用并被视为 itemId . 但是 /details/1

    这是一个 Working Sample StackBlitz 供参考。

        3
  •  1
  •   Mehdi    6 年前

    在这种情况下,您不需要在router.module中指定变量,它应该如下所示:

    {
      path: '',
      component: ItemDetailsComponent,
    },
    

    如果需要打开某个项目,请使用

    this.router.navigate(["", {itemId: 123}]);
    

    路由器

    然后需要在ItemDetailsComponent中注入 激活路由:激活路由

    this.activatedRoute.params.subscribe(
      (params) => {
        //ItemId will be available here when url changes
        console.log(params.itemId);
      }
    );