将空路径重定向到登录页面(Angular 4)

问题描述 投票:1回答:3

我想从空路径“”重定向到我的登录页面,当用户没有进入时。所以我使用警卫和儿童路线来做到这一点。但是,我的代码适用于除“”之外的所有路由。

这是我的守卫(canValidate功能)

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):boolean {
   return this.canMethod();
  }

  canMethod () {
    if (Environment.ActivateGuard) {
      let token = this._auth.getCookie(AuthorizationEnum.cookieName);
      if(token) { // token exists
        let data = {
          token: token,
          module: this.module
        };

        this._auth.validate(data, AuthorizationEnum.Bearer).subscribe(
          data => { // valid token
            if ( data.res == AuthorizationEnum.emptyResponse)  { // invalid user, it doesn't belongs to this module.
              this.letsRedirect();
            } 
            else {
              let user_role = data.det[1]; // this is the user's role!.
            }
          },
          error => { //  other error
            this.letsRedirect();
          }
        );
        return true;
      } 
      else { // user don't have token
        this.letsRedirect();
      }      
    } 
    else {
      return true;
    }    
  }


  letsRedirect(){
     window.location.href = Environment.authAppUrl + AuthorizationEnum.redirectQuery + encodeURIComponent(this.url);
  }

这是我的app-routing.module.ts(只有路由数组)

const routes: Routes = [

  // TODO: Validar esta ruta
  //{ path: '', component: LoginComponent, pathMatch: 'full' },

  //Con header
  { 
    path: '', 
    children: [
      { path: '', component: HomeComponent,canActivate:[AuthorizatedGuard]},
      { path: 'inicio', component: HomeComponent, canActivate:[AuthorizatedGuard] },  
      { path: 'categorias', redirectTo: 'base-lista/categorias'},
      { path: 'videos', redirectTo: 'base-lista/videos'},
      { path: 'base-lista/:idList', component: BaseListComponent, canActivate:[AuthorizatedGuard] },
      { path: 'base-lista/categorias/gestionar-categorias', component: CategoryVideoComponent, canActivate:[AuthorizatedGuard]  },
      { path: 'base-lista/categorias/ver-detalles-categoria', component: ViewDetailsCategoryComponent, canActivate:[AuthorizatedGuard]  },
      { path: 'base-lista/videos/gestionar-videos', component: VideoComponent, canActivate:[AuthorizatedGuard]  },
      { path: 'base-lista/videos/ver-detalles-video', component: ViewDetailsVideoComponent, canActivate:[AuthorizatedGuard]  },
     ],
    component: AppLayoutComponent,
    canActivate: [AuthorizatedGuard],
  },

  //sin header
  {
    path: '',
    component: LoginComponent,
    children: [
      {
        path: 'login',
        component: LoginComponent
      }

    ]
  }

];

当我们尝试访问“htpp:// localhost:4200 /”时,Angular将评估路径路径。配置的第一条路径的路径的第一部分是“”,所以让我们继续评估第二部分也是“”,所以我们匹配!但是警卫仍然需要验证用户是否可以访问HomeLayoutComponent(如果用户已登录)。如果用户已登录,则授予访问权限,用户将看到HomeLayoutComponent(导航栏以及HomeComponent在路由器插座中呈现),否则将重定向到“htpp:// localhost:4200 / login ”。

所以假设我们正在尝试访问“htpp:// localhost:4200 / login”。 Angular将再次评估路径路径。配置的第一个路径的路径的第一部分是“”,所以让我们继续评估第二部分是“登录”,所以我们没有匹配。我们需要评估配置的下一个路由。我们再来吧!配置的第一个路径的路径的第一部分是“”(这次),所以让我们继续评估第二部分是“登录”并且我们有一个匹配。在这种情况下,将显示LoginLayoutComponent。由于HTML模板中只有一个路由器插座,因此只显示LoginComponent。

I am using this link to create the routing

那么..我的代码出了什么问题?

angular angular-routing guard
3个回答
1
投票

你试过从你的''删除LoginComponent路径吗?这似乎是多余的。除非您使用单独的布局,否则您需要指定您正在使用的布局组件(如AppLayoutCompnent)而不是LoginComponent两次。

更改

  {
    path: '',
    component: LoginComponent,
    children: [
      {
        path: 'login',
        component: LoginComponent
      }

    ]
  }

只是

 {
    path: 'login',
    component: LoginComponent
  }

要么

  {
    path: '',
    component: LoginLayoutComponent, // <---
    children: [
      {
        path: 'login',
        component: LoginComponent
      }
    ]
  }

您应该看到的另一件事是使用路由器来处理重定向而不是window.location。这是处理它的“Angular”方式。将Router注入你的守卫并用它来导航。

letsRedirect(){
     this.router.navigate(['/login'], { queryParams: { redirectUrl: this.url } });
  }

最后,您可以使用CanActivateChild简化路线。它将对所有子路径执行检查,而不是为每个子路径添加防护。

  { 
    path: '', 
    children: [
      { path: '', component: HomeComponent,
      { path: 'inicio', component: HomeComponent },  
      { path: 'categorias', redirectTo: 'base-lista/categorias'},
      { path: 'videos', redirectTo: 'base-lista/videos'},
      { path: 'base-lista/:idList', component: BaseListComponent },
      { path: 'base-lista/categorias/gestionar-categorias', component: CategoryVideoComponent },
      { path: 'base-lista/categorias/ver-detalles-categoria', component: ViewDetailsCategoryComponent },
      { path: 'base-lista/videos/gestionar-videos', component: VideoComponent },
      { path: 'base-lista/videos/ver-detalles-video', component: ViewDetailsVideoComponent },
     ],
    component: AppLayoutComponent,
    canActivateChild: [AuthorizatedGuard],
  },

并更新你的警卫

canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):boolean

1
投票

我设法解决了我的问题,包括没有警卫重定向到登录页面的空路线,所以如果该人没有登录他将重定向他登录否则,他将输入以下定义,始终确保该人已经登录系统。

const routes: Routes = [

  // Sin header
  { path: '', component: LoginComponent, pathMatch: 'full' },

  //Con header
  { 
    path: '', 
    children: [
      { path: '', component: HomeComponent,canActivate:[AuthorizatedGuard]},
      { path: 'inicio', component: HomeComponent, canActivate:[AuthorizatedGuard] },  
      { path: 'categorias', redirectTo: 'base-lista/categorias'},
      { path: 'videos', redirectTo: 'base-lista/videos'},
      { path: 'base-lista/:idList', component: BaseListComponent, canActivate:[AuthorizatedGuard] },
      { path: 'base-lista/categorias/gestionar-categorias', component: CategoryVideoComponent, canActivate:[AuthorizatedGuard]  },
      { path: 'base-lista/categorias/ver-detalles-categoria', component: ViewDetailsCategoryComponent, canActivate:[AuthorizatedGuard]  },
      { path: 'base-lista/videos/gestionar-videos', component: VideoComponent, canActivate:[AuthorizatedGuard]  },
      { path: 'base-lista/videos/ver-detalles-video', component: ViewDetailsVideoComponent, canActivate:[AuthorizatedGuard]  },
     ],
    component: AppLayoutComponent,
    canActivate: [AuthorizatedGuard],
  },



];

ps:对不起我的英语


1
投票

这对我有用

[
  {
    path: '',
    pathMatch: 'full',
    redirectTo: 'teams'
  },
  {
    path: 'teams',
    component: TeamsComponent
  }
]

参考 - http://vsavkin.tumblr.com/post/146722301646/angular-router-empty-paths-componentless-routes

© www.soinside.com 2019 - 2024. All rights reserved.