2017-01-30 75 views
0

對於新的路由器,實際上不需要使用輔助路由,並且如果您延遲加載具有自己的路由和路由器的模塊,那麼很可能您甚至不會根據現有示例使其工作(我試過整天使用stackoverflow上的每個示例都無濟於事)。那麼這個樣子的工作例子是什麼樣的?如何使用延遲加載模塊進行子路由?

回答

3

在路由器3.3.1中使用Angular 2.3.1(angular-cli),這是我提出的工作解決方案。

頂級路由器,APP-routing.module.ts

import { NgModule } from '@angular/core'; 
import { RouterModule, Routes } from '@angular/router'; 
const routes: Routes = [ 
    { path: '', redirectTo: '/login', pathMatch: 'full', canActivate: [AuthGuard] }, 
    { path: 'login', component: AuthComponent }, 
    { path: 'analyze', loadChildren: 'app/analyze/analyze.module#AnalyzeModule', canActivate: [AuthGuard] } 
]; 
@NgModule({ 
    imports: [ RouterModule.forRoot(routes) ], 
    exports: [ RouterModule ] 
}) 
export class AppRoutingModule {} 

懶惰加載模塊(AnalyzeModule)路由器,其相應的成分爲輸出爲原始路由器出口在應用組分:

import { NgModule } from '@angular/core'; 
import { Routes, RouterModule } from '@angular/router'; 
const routes: Routes = [ 
    { path: '', component: AnalyzeComponent, 
     children: [ 
     { path: 'charts', component: ChartsComponent }, 
     { path: 'graphs', component: GraphsComponent }, 
     ] 
    } 
]; 
@NgModule({ 
    imports: [RouterModule.forChild(routes)], 
    exports: [RouterModule], 
}) 
export class AnalyzeRoutingModule { } 

懶加載組件的HTML:

<li><a href="#" [routerLink]="['charts']" routerLinkActive="active">Charts</a></li> 
<li><a href="#" [routerLink]="['graphs']" routerLinkActive="active">Graphs</a></li> 
<router-outlet></router-outlet> 

注意,因爲你懶LOA直到新的默認路徑爲空,就像在它上面的路由器中那樣。這裏的關鍵是將路由列爲兒童路由,並且不使用輔助路由器插座(無論您如何使用此特定設置,它都會失敗)。這樣做意味着您只需使用正常的routerLink(普通路由器連接器)(不附帶所有混亂的輔助插座),而不會覆蓋app-component.html中原始路由器插座中加載的懶惰組件或者下一個級別是什麼)這就是如果你不使用輔助插座並且不將子路由同時列爲兒童的情況。

這不是一個真正的新解決方案,但更多的是這種特定設置的各種解決方案的混合體。希望這會節省一些時間和挫折。

相關問題