0

I know that in Angular2, services provided by a module are available to other modules and should be provided only once.

I have a lazy-loaded MessengerModule which imports a MessengerService. I have also a HeaderModule which needs this service only for updating messages notifications.

I see two ways:

  1. Provide MessengerService at the AppModule level
  2. Provide MessengerService in MessengerModule. Import MessengerModule in HeaderModule.

In 1, it is annoying to "break" the MessengerModule by removing its logical service. In 2, I will lose the lazy loaded feature of MessengerModule which is quite big. As HeaderModule is eager loaded, Messenger will be as well right?

It seems the best choice is to provide the service at the main level. Which are your suggestions?

Mathieu Kb
  • 13
  • 4
  • Possible duplicate of [How to share service between two modules - @NgModule in angular2?](https://stackoverflow.com/questions/40089316/how-to-share-service-between-two-modules-ngmodule-in-angular2) – LarsMonty Jul 28 '17 at 16:32

1 Answers1

1

You should read this article.

It involves: app/shared/shared.module.ts

import { NgModule, ModuleWithProviders } from '@angular/core';
import { CounterService } from './counter.service';

@NgModule({})
export class SharedModule {
  static forRoot(): ModuleWithProvider`enter code here`s {
    return {
      ngModule: SharedModule,
      providers: [CounterService]
    };
  }
}

app/app.module.ts

import { SharedModule } from './shared/shared.module';

@NgModule({
  imports: [
    SharedModule.forRoot(),
    ...
  ],
  ...
})
export class AppModule {}

Since SharedModule only consists of a service that Angular registers in the root app injector, we do not need to import it in LazyModule. This is because the lazy loaded module will already have access to services defined at the root level.

JGFMK
  • 7,107
  • 4
  • 46
  • 80