Search code examples
angularionic-frameworkangular-moduleangular-providers

Lazy loading and providers strategy


Right now, using Angular v5, while using lazy loading, I load all my providers in app.module.ts which I guess isn't maybe the best strategy because this won't speed up my app boot time, specially because I've got something like 50 custom providers (don't judge me ;) ).

Therefore I'm asking my self if I should really load all of them for my all app or if I should load them only where I only use them?

I'm guessing it would be better to load providers only where I really use them.

But in such a case, it's for me then not clear at all how to solve following construct:

Let say I've got three pages (A,B and C) with their own modules and three providers (1,2 and 3).

A use 1
B use 1, 2, 3
C use 1, 2
  • I guess, since 1 is use across all the app, I would have to declare it in app.module.ts

  • Since 3 is only use in page B, I guess I would have to only declare it in B.module.ts

  • But what about 2? How could I declare it in both B.module.ts and C.module.ts with the goal to share the same provider "memory" (if the provider contains a value, both B and C should see the same object), respectively how I would code that? Simply by injecting the provider "as usual" and angular do the rest?

Thx in advance for any help, would really be appreciated

UPDATE

Not sure if I understand correctly the angular documentation but that's the goal, the providers should be loaded for the all app wide right?

See

https://angular.io/guide/ngmodule-faq#q-component-scoped-providers

UPDATE 2018

The injection strategy has evolved with the introduction of Angular v6. According the documentation it's possible with providedIn to specify in which module a service should be use. See https://angular.io/guide/dependency-injection


Solution

  • The answer is you should add your provider in app.module.ts because it is a singleton service. Here is from angular dependency injection doc:

    Dependencies are singletons within the scope of an injector

    It means when you declare your provider in app.module.ts it will be singleton in whole app and every module injected it will share the same instance of it.
    When you declare your provider in separate modules i.e B.module.ts and C.module.ts, your B page will use an instance of provider and C page will use another instance of provider. And it is not the purpose of provider.