这里是我如何处理我的孩子路线路由的例子。我认为这会帮助你,并教你使用儿童路线为你的一些组件提供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
文件中的selctory。
儿童路线 /public/public.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
保存auth所需路由和组件的安全目录。
/public/profile-component.ts
/public/profile-component.html
https://angular.io/docs/ts/latest/guide/router.html –
我见过的文档。我没有找到我在那看到的非常令人满意的东西。 –
甚至没有提到他们如何为每个模块分配一个路由文件?我认为你可以搜索'我们建议给每个功能区域自己的路由配置文件。'在该文档页面中并从该部分继续。 –