Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 在应用程序和每个模块中导入sharedModule 2_Angular - Fatal编程技术网

Angular 在应用程序和每个模块中导入sharedModule 2

Angular 在应用程序和每个模块中导入sharedModule 2,angular,Angular,我对angular 2中如何导入共享模块感到有点困惑,希望得到一些澄清 因此,当我用导入的组件和模块创建一个SharedModule类时,我也会将其导出以重用。我将SharedModule导入到我的app.module中,因此:1。它将在应用程序加载时出现。2.因此,我不必将其导入其他功能模块 我注意到,即使我在app.module中导入了,但当我运行我的应用程序时,我会收到错误消息,即我缺少组件或模块引用。因此,我最终在所有功能模块中导入了共享模块。我想通过将它放在app.module中,我就

我对angular 2中如何导入共享模块感到有点困惑,希望得到一些澄清

因此,当我用导入的组件和模块创建一个SharedModule类时,我也会将其导出以重用。我将SharedModule导入到我的app.module中,因此:1。它将在应用程序加载时出现。2.因此,我不必将其导入其他功能模块

我注意到,即使我在app.module中导入了,但当我运行我的应用程序时,我会收到错误消息,即我缺少组件或模块引用。因此,我最终在所有功能模块中导入了共享模块。我想通过将它放在app.module中,我就不必将它导入我的其他模块了

我想通过将它放在app.module中,我就不必将它导入我的其他模块了

否,导入到
AppModule
中的任何模块对于同样由
AppModule
导入的任何其他模块都不可用。如果希望功能模块可以使用
SharedModule的
导出管道/组件/指令,则必须将
SharedModule
显式导入该功能模块。这样做的好处是,您将所有导出的组件都放在一个模块中,因此,即使您必须将
SharedModule
导入10个功能模块中,您也只需进行一次导入,而不是在这10个功能模块中分别导入每个组件/指令/管道等

import { ModuleWithProviders } from '@angular/core';
import { SampleService } from './services/sample';

@NgModule({
  declarations: [],
  imports: [],
  exports: []
})

export class SharedComponentsModule {
  static forRoot(): ModuleWithProviders {
    return {
        ngModule: SharedComponentsModule,
        providers: [SampleService]
    };
}}
//Import the module with Provider in AppModule :
Imports: [
SharedComponentsModule.forRoot()
]

如需进一步参考,请查看。

如果共享组件具有组件、管道和指令,则需要将共享模块导入到每个需要它的功能模块中。作为上述情况的例外,您必须在以下场景中导入应用程序模块中的共享模块:

  • 使用延迟加载,并在不同功能模块之间共享服务,并且需要在功能模块之间创建和共享单个服务实例

    import { ModuleWithProviders } from '@angular/core';
    import { SampleService } from './services/sample';
    
    @NgModule({
      declarations: [],
      imports: [],
      exports: []
    })
    
    export class SharedComponentsModule {
      static forRoot(): ModuleWithProviders {
        return {
            ngModule: SharedComponentsModule,
            providers: [SampleService]
        };
    }}
    //Import the module with Provider in AppModule :
    Imports: [
    SharedComponentsModule.forRoot()
    ]