1

I am planning to develop a feature in Angular2 to contribute to the community.

The feature consists of one directive and one service.

I am wondering how I can best pack the feature into one module (or more modules).

  • The service must be global, so it has to be imported into the core module by the users - it cannot be imported inside lazy loaded modules
  • The directive can be imported where the user needs to use it

To make it work, I have to create two distinct modules: one to contain the service, that should be imported and re-exported by the core module; and another to contain the directive, that can either be imported where the user needs it, or globally in the shared module

Now, I kind of don't like this configuration because I have to split my feature into two modules.

Users who know how Angular2 works should be able to set it up without problems, I know, but still I would prefer if it was possible to wrap everything inside ONE module? Which are the current best practices to achieve this?

Currently I don't see any different solution: because if I put service and directive in the same module, then when I need to import the directive in a component, the service will be contained in the same import; and if the component is lazy loaded this will create a second copy of the service for that component, which would be wrong.

Thanks in advance for your help

Adriano di Lauro
  • 469
  • 4
  • 10

1 Answers1

1

Provide the service in .forRoot() of your module and require it to be imported in AppModule with MyModule.forRoot() (like is is done for example with the Router module).

Add forRoot to your module

static forRoot(config: UserServiceConfig): ModuleWithProviders {
  return {
    ngModule: CoreModule,
    providers: [
      {provide: UserServiceConfig, useValue: config }
    ]
  };
}

Also every module that wants to use the component needs to import the module with

imports: [
  BrowserModule,
  ContactModule,
  CoreModule.forRoot({userName: 'Miss Marple'}),
  AppRoutingModule
],

For more details see https://angular.io/guide/ngmodule#configure-core-services-with-coremoduleforroot

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567