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

Redirect empty path to login page (Angular 4)

我想在用户未登录时从空路径“”重定向到我的登录页面。所以我使用守卫和子路由来执行此操作。但是,我的代码适用于除“”之外的所有路线。

这是我的守卫(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);
  }

这是我的应用程序-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 将再次评估路由路径。配置的第一个路由的路径的第一部分是“”,所以让我们继续评估第二部分"login",所以我们没有匹配。我们需要评估配置的下一个路由。我们再来一次!配置的第一个路由的路径的第一部分是“”(这次),所以让我们继续评估第二部分,即 "login" 并且我们有一个匹配项。在这种情况下,会显示 LoginLayoutComponent。由于HTML模板中只有router-outlet,所以只会显示LoginComponent。

I am using this link to create the routing

所以..我的代码有什么问题?

您是否尝试过从 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

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

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:对不起我的英语

这对我有用

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

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