【问题标题】:Lazy loading of Module routing path issue模块路由路径延迟加载问题
【发布时间】:2017-06-27 04:59:38
【问题描述】:

我正在尝试使用 angular 2 延迟加载模块。

我有两个模块

  1. AppModule(主模块)
  2. ProductModule(延迟加载的模块)

AppModule.ts

@NgModule({
    imports: [
        BrowserModule,
        HttpModule,
        RouterModule.forRoot([
            { path: 'welcome', component: WelcomeComponent },
            { path: '', redirectTo: 'welcome', pathMatch: 'full' },

            { path: 'products', loadChildren:'app/products/product.module#ProductModule'}
        ])
    ],
    declarations: [AppComponent,
        WelcomeComponent
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

这里我有两条路线,一条是空白的默认路线,一条是AppModule 中的欢迎屏幕。它包含另外一个路由products 来启动模块和相关组件的延迟加载,即ProductModule

现在ProductModule 看起来像这样:

@NgModule({
    declarations: [
        ProductListComponent,
        ProductDetailComponent,
        ProductFilterPipe
    ],
    imports: [
        SharedModule,
        RouterModule.forChild([
            { path: '', component: ProductListComponent },
            { path: 'product/:id', component: ProductDetailComponent, pathMatch:'full'}
        ])
    ],
    providers: [
        ProductService,
        ProductDetailGuard
    ]
})
export class ProductModule {

}

如您所见,我的ProductModule 有空路线(用于列出产品)和一条带有product/id 的路线显示产品详细信息。

现在,ProductModule 中的第一条路线在我导航到 http://localhost:3000/products 时激活了 ProductListComponent,这没关系,但是当我导航到第二条路线时,ProductDetailComponent 被激活了导航到 http://localhost:3000/products/product/1

现在对于详细信息屏幕 url,我不想在 url 中包含 products

我已经尝试指定{ path: 'products', component: ProductListComponent } 路由。但不幸的是,它不起作用。

请解释为什么它需要详细屏幕 URL 中的产品以及如何在 http://localhost:3000/product/1 URL 上激活它?

【问题讨论】:

    标签: angular lazy-loading angular2-routing


    【解决方案1】:

    我认识这个代码。 :-) 你看过我的路由课程吗?我覆盖这个。对于延迟加载的路由,基本路由必须相同。所以两条路线都需要以“产品”开头。

    这是一个例子:

        RouterModule.forChild([
          {
            path: '',
            component: ProductListComponent
          },
          {
            path: ':id',
            component: ProductDetailComponent
          },
          {
            path: ':id/edit',
            component: ProductEditComponent,
            canDeactivate: [ProductEditGuard]
          }
        ])
    

    匹配的路由名称是必需的,因为所有延迟加载的路由都需要共享一个父路由。访问 any 子的父路由将延迟加载路由。

    【讨论】:

    • @DeborahK 有没有办法让我在不改变路线产品的情况下做到http://localhost:3000/product/1?另请提供您的课程的链接。
    • 回答您的问题...您可以删除延迟加载。然后你可以为你的路线命名任何你想要的名字。或者您可以将您的路线设为productproduct/1。他们只需要拥有相同的父路由,延迟加载就可以工作。
    猜你喜欢
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    相关资源
    最近更新 更多