0

I've got a core module named CoreModule, it contains a service named MapManagerService, directive named FlyToDirective which uses the MapManagerService, and a component named ElementComponent which uses the the flyTo.

My AppModule imports the CoreModule and uses its' components, plus has its' own MapManagerService

Reading Angular's documentation of Core Modules, you'll notice:

More precisely, Angular accumulates all imported providers before appending the items listed in @NgModule.providers. This sequence ensures that whatever we add explicitly to the AppModule providers takes precedence over the providers of imported modules.

BUT, the FlyToDirective still uses the imported CoreModule's MapManagerService, am I getting the documentation wrong?

I've figured the service that should be used is the AppModules MapManagerService and not the CoreModules

Any help would be appreciated, thanks.

Community
  • 1
  • 1
Kesem David
  • 2,135
  • 3
  • 27
  • 46

1 Answers1

0

All providers added to providers: [...] of a non-lazy-loaded module are hoisted into the applications root scope. There the same provider is registered in multiple such modules, only the one imported last takes effect.

The providers added to AppModule directly have precedence over providers of imported modules though.

You can add a provider to @Component({providers: [...]}) then, the component and it's descendants get the instance from this provider instead of the provider of the applications root scope.

Alternatively you can make the module lazy loaded. Lazy loaded modules get their own root scope and components and services in this module the the instance from this provider instead.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thanks for your quick reply! isn's setting `providers` deprecated? I've tried it and it didnt work, moreover it is not present in the `Component` d.ts – Kesem David Feb 13 '17 at 10:07
  • The `FlyToDirective` imports the `MapManagerService` of `CoreModule`, I expected the imported `MapManagerService` to be the `AppModule`'s service while using the `ElementComponent` within the `AppModule`, but instead it is still the `CoreModule`s. I want to keep the behaviour of each module the same when they're separated, but when the `CoreModule` is imported, the directive should use the `AppModule`'s `MapManagerService` – Kesem David Feb 13 '17 at 10:07
  • If you don't provide the code that demonstrates what you did, I can't help you. I have no motivation to build a mental model of the code from your verbal explanation because you could just post it. – Günter Zöchbauer Feb 13 '17 at 10:16
  • `providers` isn't deprecated. There can't be any services without `providers`. Also `providers` in `@Component()` is not deprecated if you mean that. – Günter Zöchbauer Feb 13 '17 at 10:17