如何设置身份验证路由

时间:2018-12-04 14:48:40

标签: angular

如果AppComponent中的currentUser不为null,则应用程序将转到ShellComponent。如果currentUser为null,则应用程序将转到LoginComponent。我可以从LoginComponent路由到ShellComponent,也可以在那些子级之间路由回到LoginComponent。无法正常工作的是从LoginComponent路由到ForgotPasswordComponent。我的路由设置受此video的启发,

当我尝试导航至ForgotPasswordComponent时,URI更改为localhost:4200/forgot-password,,但仍显示LoginComponent。控制台中没有错误。

安装程序看起来像它的原因是因为我不想要ShellComponent中的任何元素,例如<div class="wrapper"><app-sidebar>等将出现在LoginComponent,ForgotPasswordComponent或ShellComponent之外的任何其他组件中。

这是怎么回事?
要使我的路线正常运行,必须做些什么?

路线

RouterModule.forRoot([
  {
    path: '', component: ShellComponent,
    children: [
      { path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
      { path: 'schedule', component: ScheduleComponent, canActivate: [AuthGuard] },
      { path: 'division', component: DivisionComponent, canActivate: [AuthGuard] },
      { path: 'result', component: ResultComponent, canActivate: [AuthGuard] },
      { path: 'statistics', component: StatisticsComponent, canActivate: [AuthGuard] },
      { path: 'rules', component: RulesComponent, canActivate: [AuthGuard] },
      { path: 'contact', component: ContactComponent, canActivate: [AuthGuard] }
    ]
  },
  { path: 'login', component: LoginComponent },
  { path: 'forgot-password', component: ForgotPasswordComponent }     
])

app.component.html

<!-- If user is already logged in -->
<router-outlet *ngIf="currentUser"></router-outlet>

<!-- If user is logged out -->
<app-login *ngIf="!currentUser"></app-login>

shell.component.html

<div class="wrapper">
  <app-sidebar></app-sidebar>
  <div class="main-panel">
   <app-navbar></app-navbar>
   <div class="content">
       <router-outlet></router-outlet>
   </div>
   <app-footer></app-footer>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

我认为您仅应在app-html中使用router-outlet,然后才可以使用。

app.component.html

<router-outlet></router-outlet>

您还可以在canActivateChild的每个子路由上使用canActivate来代替ShellComponentcanActivateChild可以在父级上使用,并且也会对其子级起作用,请参见https://angular.io/api/router/CanActivateChild

相关问题