首页 > 解决方案 > Angular 9.1.9 带参数的条件路由

问题描述

语境:

我有一个后退和继续按钮,可以通过各个阶段和他们的子步骤进入向导。

问题:

我有以下路由:

{
    path: 'test/stage/1',
    component: WizardComponent,
    children: [
      {
        path: 'step/1',
        component: Stage1Step1Component,
      },
      {
        path: 'step/2',
        component: Stage1Step2Component,
      }   
    ]
  },
  {
    path: 'test/stage/2',
    component: WizardComponent,
    children: [
      {
        path: 'step/1',
        component: Stage2Step1Component,
      },
      {
        path: 'step/2',
        component: Stage2Step2Component,
      }   
    ]
  },

问题是我希望由各种 url 加载的组件是非常具体的组件,因此我想避免共享 StepComponent,因为每条路由都在执行非常特定的任务。

我需要说:

如果是第 1 阶段,则加载 x 组步骤,但如果是第 2 阶段,则加载 y 组步骤。

我遇到的问题是,当我进入 stage/2/step/1 时,它会再次加载 WizardComponent,我想避免这种情况。

有没有一个不错的方法

test/stage/:stage

同时还可以有条件地选择使用哪些孩子?

也许是这样的?

{
    path: 'test/stage/:stage',
    component: WizardComponent,
    children: [
      {
        path: '1/step/1',
        component: Stage1Step1Component,
      },
      {
        path: '1/step/2',
        component: Stage1Step2Component,
      }   
      {
        path: '2/step/1',
        component: Stage2Step1Component,
      },
      {
        path: '2/step/2',
        component: Stage2Step2Component,
      }   
    ]
  }

(以上行不通)

标签: angular

解决方案


我是个白痴,其实很简单:

我只需要这样做:

{
    path: 'test',
    component: WizardComponent,
    children: [
      {
        path: 'stage/1/step/1',
        component: Stage1Step1Component,
      },
      {
        path: 'stage/1/step/2',
        component: Stage1Step2Component,
      }   
      {
        path: 'stage/2/step/1',
        component: Stage2Step1Component,
      },
      {
        path: 'stage/2/step/2',
        component: Stage2Step2Component,
      }   
    ]
  }

尽管稍后我将研究延迟加载模块的事情,但显然这不是很漂亮,需要这样做以了解我在哪个阶段和步骤上作为 url 的入口点:

// This is wrong and horrible, but can't figure out another way yet. Perhaps lazyprovider in the route?
let stageNumber = parseInt(window.location.pathname.split("/")[3]) // parseInt(this.route.parent.snapshot.url[2].path);
let stepNumber = parseInt(window.location.pathname.split("/")[5]) // parseInt(this.route.parent.snapshot.url[4].path);

推荐阅读