代码之家  ›  专栏  ›  技术社区  ›  Jimmyt1988

Angular 9.1.9带参数的条件路由

  •  0
  • Jimmyt1988  · 技术社区  · 4 年前

    背景:

    我有一个后退和继续按钮,可以在向导中遍历各个阶段及其子步骤。

    问题:

    我有以下路线:

    {
        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,
          }   
        ]
      }
    

    (以上不起作用)

    0 回复  |  直到 4 年前
        1
  •  0
  •   Jimmyt1988    4 年前

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

    我只需要这样做:

    {
        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);