在AppModule中导入的共享模块 [英] Shared module imported in AppModule

查看:211
本文介绍了在AppModule中导入的共享模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关模块的Angular文档,寻找不鼓励在AppModule中导入SharedModule的行.

我没有发现任何有关它的信息,只是一个GitHub问题,指出最好不要将其导入.但是,没有任何深入的解释...

https://github.com/tomastrajan/angular-ngrx- material-starter/issues/47

我不赞成在共享模块中提供服务.但是没有别的.

所以我的问题是:

由于我所有的功能模块都是延迟加载的,并且需要导入共享模块,而且我的应用程序组件也需要使用同一共享模块提供的内容,因此将其导入AppModule是一种不好的做法吗?/p>

后果可能是什么?

提前感谢任何人

解决方案

SharedModule导入到AppModule中的问题在于,提供程序将在功能模块中注入两次(一次是SharedModuleAppModule)一次,这将导致服务不像预期的那样单身.

要实现的通用模式不是直接在@NgModule声明上公开提供程序,而是在静态forRoot函数(名称不是强制性的,这是一个约定)中公开提供程序,如下所示:

export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
         ...
      ]
    };
  }
}

SharedModule导入到AppModule中时,请使用SharedModule.forRoot(),将其导入到功能模块中时,只需将其导入为SharedModule

I was reading the Angular documentation about modules, looking for a line that discourages importing a SharedModule inside the AppModule.

I didn't find anything about that, just a GitHub issue which states that it's better not to import it. However without any deep explain...

https://github.com/tomastrajan/angular-ngrx-material-starter/issues/47

Angular discourages providing services in the Shared modules, which indeed I agree. But nothing else.

So my question is:

Since all my feature modules are lazy-loaded, and needs to import the shared module, but also my app component needs to use stuff provided by the same shared module, is it a bad practice to import it into the AppModule?

What may the consequences be?

Thanks in advance to anyone

解决方案

The problem with importing a SharedModule into the AppModule is that the providers will be injected twice in the feature modules (once by the SharedModule, once by the AppModule) which will result in the services not being singletons as they are supposed to be.

The common pattern to achieve that is not to expose providers directly on the @NgModule declaration but in a static forRoot function (the name is not mandatory, it's a convention) like that:

export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
         ...
      ]
    };
  }
}

When importing the SharedModule into AppModule, use SharedModule.forRoot(), when you import it in a feature module just import it as SharedModule

这篇关于在AppModule中导入的共享模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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