您可以使用子路徑爲不同的視圖使用不同的佈局。
這裏是Angular2
使用兒童路線的一個常見的例子我喜歡用孩子的路線在我的角度2個應用程序的安全頁面和不安全頁面分開。
在我的應用程序的根,我有兩個目錄
/Public
&
/Secure
現在在根目錄下我也有
/app.routing.ts
從那裏
我創建佈局文件夾,
/layouts
在該目錄中創建
/layouts/secure.component.ts
/layouts/secure.component.html
&
/layouts/public.component.ts
/layouts/public.component.html
從這個角度,我可以轉移我的路線,根據網頁是否意味着是安全的或公共的兩種佈局之一。我通過創建一個路由到我的根routes.ts文件中的每個佈局。
/app.routes.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 }
];
請注意,我登記我的孩子的路線爲每個佈局。這是每個單獨路由文件的導出值。一個在公共目錄中,另一個在安全目錄中。
/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 },
{ path: 'benefits', component: BenefitsComponent },
{ path: 'services', component: ServicesComponent },
{ path: 'education', component: EducationComponent },
{ path: 'products', component: ProductsComponent },
{ path: 'fcra', component: FcraComponent },
{ path: 'croa', component: CroaComponent },
{ path: 'building', component: BuildingComponent },
{ path: 'tips', component: TipsComponent },
{ path: 'maintenance', component: MaintenanceComponent }
];
所有這些路線現在作爲我的公共佈局的子路由訪問。現在,我們可以保護我們的安全視圖。
所以在安全目錄基本上我做同樣的事情,
/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 },
{ path: 'recommendations', component: RecommendationsComponent },
{ path: 'score-simulator', component: ScoreSimulatorComponent },
{ path: 'payment-method', component: PaymentMethodComponent },
{ path: 'lock-account', component: LockAccountComponent }
];
這允許我使用auth
現在保護這些孩子的路線。如果您在
/app.routes.ts記得我們這樣做是爲了安全的路線,
{ path: '', component: SecureComponent, canActivate: [Guard], data: { title: 'Secure Views' }, children: SECURE_ROUTES }
通知的[Guard]
。這使我們能夠保護所有的兒童路線以實現安全佈局。這是我使用兒童路線的一個原因。我可以給你更多,但我覺得這是最合理的解釋。
只是爲了進一步採取一些措施,並把這個角度給你,這是我如何[Guard]
安全網頁。創建服務和implementing CanActivate
@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;
}
}
這可以讓你成爲大衆佈局<router-outlet></router-outlet>
然後使用佈局不同的頁眉和頁腳。然後在安全佈局中再次使用<router-outlet></router-outlet>
,顯然是不同的頁眉和頁腳。 讓我知道如果我有什麼不清楚的,我會更新答案。
它應該是,直到你實現類似卡片的東西相同的佈局佈局。 –