角度2/4条件分量路由?

时间:2017-12-16 22:07:13

标签: angular routes

我希望我的所有登录/非登录页面都在同一条路线中,让我们说root“/”,我们可以在不同的条件下将不同的组件设置为路径吗?

下面是我的路线设置。如果我可以设置路径:''到HomeComponent登录时, 并设置路径:''到UnauthorizedHomeComponent没有登录?请参阅下面的评论

我的路线设置:

const routes: Routes = [
  { path: '', component: HomeComponent, // Want to set to UnauthorizedHomeComponent while not logged in
  { path: 'dashboard', component: DashboardComponent,canActivate: [AuthGuard]},
  { path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] },
  { path: 'login', component: LoginComponent },
  { path: 'register', component: RegisterComponent }
];
export const AppRouting = RouterModule.forRoot(routes, { 
  useHash: true
});

在我的app.module

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    RegisterComponent,
    ProfileComponent,
    HomeComponent,
    DashboardComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    FormsModule,
    CustomFormsModule,
    AppRouting  //Routes
  ],
  providers: [AuthService, AuthGuard, JwtHelper],
  bootstrap: [AppComponent]
})
export class AppModule { }

1 个答案:

答案 0 :(得分:0)

我们不能在家中使用Router.navigate([])来决定降落地点吗? 例如

export class HomeComponent {
   loggedIn:boolean = true;
   constructor(private router:Router){}

   ngOnInit(){
     if(!this.loggedIn){
        this.router.navigate(["/login"]);
     }
   }
}

@NgModule({
   declarations: [
      AppComponent, HomeComponent, UnAuthHomeComponent
   ],
   imports: [
      BrowserModule, FormsModule,
      RouterModule.forRoot([
        {path: '', component: HomeComponent},
        {path: 'shopping', component: ShoppingComponent},
        .....
      ])
   ],
   bootstrap: [AppComponent]
})
export class AppModule{

}

此控件将转到HomeComponent,根据您的情况,您可以导航到所需的组件。