首页 文章

在延迟加载的模块中使用Angular组件

提问于
浏览
5

我想在我的应用程序的几个部分中使用Angular组件,包括在延迟加载的模块中的组件中 . 我不知道如何声明组件在惰性模块中使用它 . 我将向您展示不同文件的一些相关部分:

app.module.ts

import { FpgTimeComponent } from './fpgTime/fpg-time.component';


@NgModule({
  declarations: [
      AppComponent, 
      (...)
      FpgTimeComponent

app.routing.ts

const appRoutes: Routes = [

    { path: '', redirectTo: 'customer', pathMatch: 'full' },
    {
        path: 'customer',
        component: CustomerComponent
    },
    {
        path: 'lazy',
        loadChildren: 'app/lazy/lazy.module#LazyModule'
    }
];

lazy.module.ts

import { FpgTimeComponent } from '../fpgTime/fpg-time.component';

import { LazyComponent }   from './lazy.component';
import { routing } from './lazy.routing';

@NgModule({
    imports: [routing],
    declarations: [
        LazyComponent, 
        FpgTimeComponent
    ]
})

该应用程序加载,但当我进入惰性路由时,它会抛出以下错误:

Uncaught(承诺):错误:类型FpgTimeComponent是2个模块声明的一部分:AppModule和LazyModule!请考虑将FpgTimeComponent移动到导入AppModule和LazyModule的更高模块 . 您还可以创建一个新的NgModule,它导出并包含FpgTimeComponent,然后在AppModule和LazyModule中导入该NgModule .

我没有在任何地方导入LazyModule,因为它是懒惰加载的 . 那么,我如何声明组件FpgTimeComponent能够在惰性模块(以及非惰性组件)中使用它?

提前致谢,

1 回答

  • 3

    FpgTimeComponent 不是将要加载的延迟模块的文件的一部分,因此您可以在该模块中定义't do that. Think about it, you are trying to import a component in the lazy module that the module knows nothing about since it isn't,并且未在 LazyModule 中导入的任何其他模块中定义它 . 那么从哪里获取组件?

    FpgTimeComponent 添加到 SharedModule 并导入 LazyModule 中的 SharedModule ,或将 FpgTimeComponent 移动到 LazyModule . 一旦你做了其中之一,它应该工作 .

    无论如何,这是一种更好的方法,因为我可以保证,随着您的不断开发,您将与其他组件/其他惰性模块保持同样的错误 . 如果您在多个位置使用组件,那么它们应该位于 SharedModuleAngular best practices defines,并且 SharedModule 应该在所有惰性模块中导入 .

    这是一个例子 .

    SharedModule:

    import { FpgTimeComponent } from './some/path';
    
    @NgModule({
        declarations: [
            FpgTimeComponent
        ],
        exports: [
            FpgTimeComponent
        ]
    })
    

    LazyModule:

    import { SharedModule } from '../shared/shared.module';
    
    import { LazyComponent }   from './lazy.component';
    import { routing } from './lazy.routing';
    
    @NgModule({
        imports: [
            routing,
            SharedModule
        ],
        declarations: [
            LazyComponent
        ]
    })
    

相关问题