這裏是我如何處理我的孩子路線路由的例子。我認爲這會幫助你,並教你使用兒童路線爲你的一些組件提供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 –
我見過的文檔。我沒有找到我在那看到的非常令人滿意的東西。 –
甚至沒有提到他們如何爲每個模塊分配一個路由文件?我認爲你可以搜索'我們建議給每個功能區域自己的路由配置文件。'在該文檔頁面中並從該部分繼續。 –