我认为我以一种更合乎逻辑的方式来做这件事。我想这是一种意见。secured pages我用和分隔我的应用程序public pages。我为每组使用模板。所以public component,然后secure component把guard。secure template
确保您添加[Guard]到需要保护的完整路线。
因此,当我确保一条路线时,我会将父母添加到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 }
];
export const routing = RouterModule.forRoot(APP_ROUTES);
确保注意到这条线,
{ path: '', component: SecureComponent, canActivate: [Guard], data: { title: 'Secure Views' }, children: SECURE_ROUTES }
所以我创建了 2 个布局
/public/ 所有公共组件
/public/public.routes.ts
/secure/ 所有安全组件
/secure/secure.routes.ts
安全路线
请注意,这些路由现在不需要Guard,因为它由模板父级处理。
export const SECURE_ROUTES: Routes = [
{ path: '', redirectTo: 'overview', pathMatch: 'full' },
{ path: 'items', component: ItemsComponent },
{ path: 'overview', component: OverviewComponent },
{ path: 'profile', component: ProfileComponent },
];
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 }
];
export const routing = RouterModule.forRoot(APP_ROUTES);
在目录 /layouts 我创建了一个布局
/layouts/secure.component.ts
/layouts/secure.component.html
/layouts/public.component.ts
/layouts/public.component.html
一切都通过布局布线,或者public是安全的。secure[Guard]
然后我使用本地存储中的令牌处理身份验证。
@Injectable()
export class Guard implements CanActivate {
constructor(protected router: Router, protected auth: Auth ) {}
canActivate() {
if (localStorage.getItem('access_token')) {
// logged in so return true
return true;
}
// not logged in so redirect to login page
this.router.navigate(['/home']);
return false;
}
}
一旦我像这样设置我的应用程序,我就会将所有需要安全的路由放在安全目录中,并将公共路由放在公共位置。然后我在他们各自目录中的 public.routes.ts 文件或 secure.routes.ts 文件中创建他们的路由。