如何根据条件重定向角度4路线

时间:2018-03-14 11:13:32

标签: angular redirect conditional angular4-router

取决于用户类型,我必须在路径为空时重定向到页面。因此,我尝试了以下方式。

export const Approutes: Routes = [
      { path: '', pathMatch: 'full'},
      {
        path: 'locals',  component: LaunchScreenComponent,
          children: [
            {
            path: 'home',
            component: HomeScreenComponent,
          },
          {
              path: 'change-password',
              component: ChangePasswordComponent
          }
        ]
      }
];
if(Approutes[0].path.length == 0){
  if(sessionStorage.authToken){
    if(sessionStorage.user1 == 'true'){
       Approutes[0].redirectTo = '/user1/manage';
   } else if(!sessionStorage.user1 && sessionStorage.user2 == 'false'){
     Approutes[0].redirectTo = '/user2/listing';
  } else{
    Approutes[0].redirectTo = '/locals/home';
  }
 } else {
    Approutes[0].redirectTo = '/locals/home';
 }
}

enter image description here  有效。但是,当我为prod构建时,它会给出错误。错误是:应该有redirectTo或组件bla bla中的任何一个.. 任何人都可以帮助我。

1 个答案:

答案 0 :(得分:1)

你有没有尝试过:

export const Approutes: Routes = [
  {
    path: 'locals',  component: LaunchScreenComponent,
      children: [
        {
        path: 'home',
        component: HomeScreenComponent,
      },
      {
          path: 'change-password',
          component: ChangePasswordComponent
      }
    ]
  }
];
if(sessionStorage.authToken){
    if(sessionStorage.user1 == 'true'){
        Approutes.unshift({ path: '', pathMatch: 'full', redirectTo: '/user1/manage'});
    } else if(!sessionStorage.user1 && sessionStorage.user2 == 'false') {
        Approutes.unshift({ path: '', pathMatch: 'full', redirectTo: '/user2/listing'});
    } else{
        Approutes.unshift({ path: '', pathMatch: 'full', redirectTo: '/locals/home'});
    }
} else {
    Approutes.unshift({ path: '', pathMatch: 'full', redirectTo: '/locals/home'});
}

不会影响您的流量并消除prod错误。