【问题标题】:How to redirect angular 4 route based on conditons如何根据条件重定向角度 4 路线
【发布时间】:2018-08-22 21:30:41
【问题描述】:

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

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';
 }
}

有效。但是,当我为产品构建时它会出错。错误是:应该有任何一个redirectTo或组件bla bla .. 谁能帮帮我。

【问题讨论】:

    标签: angular redirect conditional angular4-router


    【解决方案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 错误。

    【讨论】:

    • 这么简单的技术。我没有尝试。感谢您的回答。这是实现这一目标的正确方法吗?只是想知道
    • 是的,它完全可以做到这一点。如果您解决了问题,则必须将新的navigation 设置为所需的路径。
    • 您好,感谢您的回复。上述错误已解决,但无法读取 null 的属性参数。你能告诉我是什么错误
    • 请检查我上传的有问题的图片
    • 你能让代码在 git 上可用或在 stackblitz 上运行吗?
    猜你喜欢
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 2019-09-21
    • 1970-01-01
    • 2014-06-05
    相关资源
    最近更新 更多