带有子路由的Angular 2路由器通配符处理 [英] Angular 2 Router Wildcard handling with child-routes

查看:79
本文介绍了带有子路由的Angular 2路由器通配符处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当将子路由与angular2的路由器"3.0"一起使用时,无需在父路由器配置中声明它们(之前,您必须在父组件中执行类似/child...的操作).

When using child routes with angular2's router "3.0", there is no need to declare them in the parent router config (before, you had to do something like /child... in the parent component).

我想配置一个全局的找不到页面"处理程序,我可以这样:

I want to configure a global "page not found" handler, which I can do like this:

{ path: '**', component: PageNotFoundComponent }

在我的应用程序路由模块中.

in my app routing module.

警告:如果执行此操作,则路由器会导航至PageNotFoundComponent之前在应用程序路由模块中声明的路由.但是,当我尝试访问子路由时,它总是导航到通配符路由(在某些子路由模块中使用RouterModule.forChild声明.

The caveat: If I do this, the router navigates to routes declared in the app routing module before the PageNotFoundComponent just fine. But it always navigates to the wildcard route when I try to access a child route (declared using RouterModule.forChild in some child routing module.

直觉上,通配符路由应该放在所有其他路由配置的后面,因为路由器以声明顺序进行解析.但是似乎没有办法在子路由之后声明它.在所有子路由器模块中声明通配符路由似乎也不太好.

Intuitively, the wildcard route should be placed behind all other route configs, because the router resolves in declaration order. But there does not seem to be a way to declare it after the child routes. It also does not seem very elegant to declare a wildcard route in all child router modules.

我丢失了某些东西吗?还是在使用子路由时没有办法在Angular-2-Router-3中定义全局404页?

Am I missing something or is there just no way to define a global 404-page in Angular-2-Router-3 when using child routes?

推荐答案

您可以轻松地使用集中式通配符路由,即针对站点范围内的找不到页面"组件.只需将其提取到单独的路由模块中,该模块将包含在包含子路由的所有其他模块之后.

You can easily have a centralized wildcard route, i.e. for a site-wide 'Page not found' component. It simply has to be extracted into a separate routing module, which gets included after all the other modules containing child routes.

因此,通配符路由确实位于最后位置,并且不会在任何后续模块中隐藏该路由.

Therefore, the wildcard route is truly in last position and doesn't hide the routes from any following module.

@NgModule({
    imports: [
        RouterModule.forChild([
            {
                path: '**',
                component: NotFoundComponent
            }
        ])
    ],
    declarations: [
        NotFoundComponent
    ],
    exports: [
        RouterModule
    ]
})
export class WildcardRoutingModule { }

应用程序模块:

@NgModule({
    imports: [
        BrowserModule,

        AppRoutingModule, // Has forRoot routes 

        HomeModule, // Has forChild routes 
        LoginModule, // Has forChild routes
        ProductModule, // Has forChild routes
        DiagnosticsModule, // Has forChild routes

        WildcardRoutingModule // Last position
    ],
    declarations: [
        AppComponent  
    ],
    providers: [
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}

这篇关于带有子路由的Angular 2路由器通配符处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆