【问题标题】:How to add routes to an Angular Modules only when Eagerly loaded仅在急切加载时如何将路由添加到 Angular 模块
【发布时间】:2019-02-05 07:24:51
【问题描述】:

我有一个包含一些路由的模块:

export const routes: Routes = [
    {
        path: '/some-util-path',
        component: SomeUtilComponent
    }
];

@NgModule({
    imports: [
        CommonModule,
        FormsModule,
        RouterModule.forRoot(routes)
    ],
    declarations: [
        // --- some components ---
    ],
    providers: [
        // --- some services ---
    ],
    exports: [
        // --- some exports ---
    ],
})
export class MyUtilModule {

}

当我在 app.module(根模块)中导入这个模块时,它工作正常,但是当我(以及)在延迟加载的模块中导入它时,我得到了

Error: RouterModule.forRoot() called twice. 
Lazy loaded modules should use RouterModule.forChild() instead.

如何配置此 Util 模块以根据其用例将路由加载为 forRoot 和 forChild?

我想我可能会将路由和“SomeUtilComponent”拆分到另一个模块,我只在 app.module 中加载,但我很想知道仅使用一个模块和条件逻辑是否可行。

我正在阅读静态 forRoot 和 forChild 方法,但我不知道如何安排导入,因为您只能指定提供程序。

【问题讨论】:

    标签: angular angular-routing


    【解决方案1】:

    您好,我认为您需要export const routing: ModuleWithProviders = RouterModule.forChild(routes); 才能使路由工作这里是一个示例:

    const routes: Routes = [{ path: '', component: LazyComponent }];
    export const routing: ModuleWithProviders = RouterModule.forChild(routes);
    

    然后在你的延迟加载模块中执行下一个:

    @NgModule({
      imports: [routing],
      declarations: [LazyComponent]
    })
    export class LazyModule {}
    

    这是一篇文章: Lazy Loading a Module

    来自Angular IO concerning lazy loading

    您可能已经注意到 CLI 将 RouterModule.forRoot(routes) 添加到 app-routing.module.ts 导入数组中。这让 Angular 知道这个模块 AppRoutingModule 是一个路由模块,并且 forRoot() 指定这是根路由模块。它配置你传递给它的所有路由,让你访问路由器指令,并注册 RouterService。在 AppRoutingModule 中使用 forRoot(),即在根级别的应用程序中使用一次。 CLI 还将 RouterModule.forChild(routes) 添加到功能路由模块。这样,Angular 就知道路由列表只负责提供额外的路由,并且是为功能模块设计的。您可以在多个模块中使用 forChild()。

    【讨论】:

    • 感谢您的回复,但问题是我有一个实用模块(带有路由),我事先不知道这个实用模块是否会在 app.module 中急切加载或(可能作为依赖项) 在延迟加载的模块中延迟加载。我看不到您的示例如何解决此问题。
    • @mvermand 我只是在这里给出一些主要思想,你应该只在应用程序/模块级别使用 forRoot(),每个子模块都应该导入它的路由 forChild() 请查看编辑版本
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    • 2021-12-30
    • 2020-07-26
    • 1970-01-01
    相关资源
    最近更新 更多