有条件的子路由(角度)

时间:2019-01-31 02:53:04

标签: angular routing navigation parent-child

是否可以有条件地默认显示子路线?

我正在尝试让用户登陆特定的子路线,具体取决于他们过去的订购方式(即登陆商店,在线或社交网站的频道页面)。

如果他们是从商店订购的,则转到商店子路线。
如果未从商店订购,则转到在线子路线。
如果他们未从商店/儿童处订购,则转到社交。

用户必须从> 1个频道订购。

以下内容有效,但如果我从某个页面单击以单击频道,然后在浏览器上单击“上一步”,则“频道”页面显示为空白(即,该应用似乎默认为路由器出口的空白页面。

下面是我的路由器模块

   {
      path: 'Channel/:id',
      component: ChannelComponent,
      children: [
        {
          path: 'Store', component: StoreComponent
        },
        {
          path: 'Online', component: OnlineComponent
        },
        {
          path: 'Social', component: SocialComponent
        }
      ]
    }

下面是我的channel.component.ts

   ngOnInit(): void {
      this.orderedFromChannel= this.getTypes(this.userId); 
      if (this.orderedFromChannel['Store']) {
        this.showStore();
      } else if (this.orderedFromChannel['Online']) {
        this.showOnline();
      } else if (this.orderedFromChannel['Social']) {
        this.showSocial();
      } 
    }

      showStore() {
        this.router.navigate(["Store"], {relativeTo: this.route})
      }
      showOnline() {
        this.router.navigate(["Online"], {relativeTo: this.route})
      }
      showSocial() {
        this.router.navigate(["Social"], {relativeTo: this.route})
      }

下面是我的channel.component.html

<router-outlet></router-outlet>

1 个答案:

答案 0 :(得分:0)

要设置默认路由,您可以在子数组的底部设置一个空路径“”。因此,如果两个孩子的路线都不匹配,它将转到最后一条路径。像这样:

{
  path: 'Channel/:id',
  component: ChannelComponent,
  children: [
    {
      path: 'Store', component: StoreComponent
    },
    {
      path: 'Online', component: OnlineComponent
    },
    {
      path: 'Social', component: SocialComponent
    },
    {
      path: '', component: StoreComponent //if you want store to be default
    },
  ]
}

或者,您可以使用重定向:

{
  path: 'Channel/:id',
  component: ChannelComponent,
  children: [
    {
      path: 'Store', component: StoreComponent
    },
    {
      path: 'Online', component: OnlineComponent
    },
    {
      path: 'Social', component: SocialComponent
    },
    {
      path: '', redirectTo: 'Store' //if you want store to be default
    },
  ]
}
相关问题