这是我如何使用子路由处理路由的示例。我认为这将帮助您并教您使用子路由为您的某些组件提供Guard。如果用户缺少身份验证,这将保护某些视图。我在public 和secure 中分开我的,通过布局路由所有内容,然后加载选择任何布局的路由。
确保导出子路由并在布局路由中调用正确的路由。还要确保在每个子路由文件中使用redirectTo。
我们将布局定义为公开或安全。然后在每个目录中提供路由文件,以便在选择创建路由后接管。
app.routing.ts
const APP_ROUTES: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full', },
{ path: '', component: PublicComponent, data: { title: 'Public Views' }, children: PUBLIC_ROUTES },
{ path: '', component: SecureComponent, canActivate: [Guard], data: { title: 'Secure Views' }, children: SECURE_ROUTES }
];
然后我有一个布局文件夹
布局
layouts/public/public.components.ts
layouts/public/public.components.html
layouts/secure/secure.components.ts
layouts/secure/secure.components.html
secure.component.ts 是这样的布局,
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Auth } from './../services/auth.service';
@Component({
providers: [ Auth ],
selector: 'app-dashboard',
templateUrl: './secure.component.html'
})
export class SecureComponent implements OnInit {
constructor( private router: Router, private auth: Auth ) { }
ngOnInit(): void { }
}
然后在您的安全目录中,您可以创建一个组件并选择您将用于它的模板,
@Component({
providers: [ Auth ],
templateUrl: './profile.component.html'
})
export class ProfileComponent implements OnInit {
constructor( private router: Router, private auth: Auth, private http: Http ) { }
ngOnInit() { }
}
现在确保在安全和公共目录中创建您的子路由。一旦路由被击中,子路由将加载正确的类并呈现模板文件。
请记住,它们将是您的布局的子级。因此,您可以在secure.component.html 中放置导航栏和页脚,它将显示在您的所有安全组件中。因为我们使用选择器来加载内容。您的所有安全和公共组件都将加载到布局html 文件内的选择中。
子路线
/public/piublic.routes.ts
export const PUBLIC_ROUTES: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'p404', component: p404Component },
{ path: 'e500', component: e500Component },
{ path: 'login', component: LoginComponent },
{ path: 'register', component: RegisterComponent },
{ path: 'home', component: HomeComponent }
];
/secure/secure.routes.ts
export const SECURE_ROUTES: Routes = [
{ path: '', redirectTo: 'overview', pathMatch: 'full' },
{ path: 'items', component: ItemsComponent },
{ path: 'overview', component: OverviewComponent },
{ path: 'profile', component: ProfileComponent },
{ path: 'reports', component: ReportsComponent }
];
总结
我们在Angular2 应用程序的根目录中设置了一个初始路由文件。此路由文件根据用户是否经过身份验证将流量定向到两种布局之一。如果他们对所提供的任何路线公共布局或安全布局具有身份验证。然后,这些布局中的每一个都有一堆子路由和组件,它们被提供给各自的布局。
所以要清理文件结构,
root = /
您控制查看哪个布局的主应用程序路由。
/app.routing.ts
保持布局安全或公开的布局。
公开
`/layouts/public.components.ts
/layouts/public.components.html
/layouts/public.routing.ts`
安全
`/layouts/secure.components.ts
/layouts/secure.components.html
/layouts/secure.routing.ts`
公共目录,其中包含无需身份验证即可查看的任何内容。
/public/home-component.ts
/public/home-component.html
保存身份验证所需路由和组件的安全目录。
/public/profile-component.ts
/public/profile-component.html