2017-10-07 115 views
2

我正在一個新的Angular應用程序有多個模塊。我仍然努力讓我的路由正確。在下面的(簡化)例子中,我想懶加載StoreModule。如果沒有給出網址,我想我的應用程序重定向到/store。如果給出了無效的URL,我想要顯示我的NotFoundComponent。但是,在我當前的配置中,始終顯示NotFoundComponent,無論URL如何。你們看到我在做什麼錯了嗎?角度懶加載路由總是去通配符模塊

這是我的app.module.ts文件,我希望它只使用NotFoundModule中提供的RouterModule,如果沒有可以匹配的URL。

app.module.ts

@NgModule({ 
    declarations: [ 
    AppComponent 
    ], 
    imports: [ 
    BrowserModule, 
    AuthModule, 
    RouterModule.forRoot([ 
     { path: '', redirectTo: 'store', pathMatch: 'full'}, 
     { path: 'store', loadChildren: 'app/store/store.module#StoreModule'}, 
     { path: 'login', component: LoginComponent }, 
    ]), 
    LoginModule, 
    NotfoundModule, 
    ], 
    bootstrap: [AppComponent], 
    exports: [RouterModule] 
}) 
export class AppModule { } 

這是我的StoreModule。如果我註釋掉我的app.module.ts模塊中的NotFoundModule,這一切都按預期工作。

store.module.ts

@NgModule({ 
    imports: [ 
    AuthModule, 
    CommonModule, 
    SharedModule, 
    RouterModule.forChild([ 
     { path: '', pathMatch: 'full', redirectTo: 'dashboard' }, 
     { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }, 
    ]), 
    ], 
    declarations: [StoreTemplateComponent, DashboardComponent] 
}) 
export class StoreModule { } 

notfound.module.ts

@NgModule({ 
    imports: [ 
    CommonModule, 
    RouterModule.forChild([ 
     { 
     path: '**', 
     component: NotfoundComponent 
     } 
    ]) 
    ], 
    declarations: [ NotfoundComponent ], 
}) 
export class NotfoundModule { } 
+0

不過不幸的是(這在通配符路由中甚至是相關的嗎?) – hY8vVpf3tyR57Xib

回答

0

你的路由器的設置看起來OK。有一點需要注意的是 你在'儀表板'中必須重定向 ,並且重定向URL必須是錯誤的, 因此你被重定向到NotFoundComponent。

希望這可以解決您的問題。

0

如果沒有給出url,我希望我的應用程序重定向到/ store。如果給出了無效的URL,我希望顯示我的NotFoundComponent。

如果這是需求,那麼您需要刪除notfound.module.ts。或者您需要像目前設置一樣懶惰地加載它,而不是將其加載到路由中,並將其添加到應用程序模塊中,並加載到前端,並將所有路線視爲通配符。

您可以只有一個NotfoundComponent並將其添加到您現有的路線。

RouterModule.forRoot([ 
    { path: '', redirectTo: 'store', pathMatch: 'full'}, 
    { path: 'store', loadChildren: 'app/store/store.module#StoreModule'}, 
    { path: 'login', component: LoginComponent }, 
    { path: '**', component: NotfoundComponent } // this should work 
]),