2017-10-07 114 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 
]),