1

In Angular 1 all Services and Directives had to be added to the Angular Application before the Bootstrap Phase. Angular 2 has a new concept of injection and has introduced hierarchical Injectors. Do hierarchical Injectors enable you to add Services and Components in Angular2 after the Bootstrap Phase.

Tobias Willig
  • 1,124
  • 7
  • 16

1 Answers1

1

No, you need to add providers statically and therefore they need to be known and registered at bootstrap time.

The hierarchy of injectors is determined by the components and directives hierarchy and providers are configured in static component and directives metadata. There is nothing you can modify at runtime.

You can create an independent injector hierarchy or a sub-hierarchy of a component/directive injector unrelated to components where you can configure providers at runtime.

If you instantiate or create components dynamically at runtime you can somehow work around and define providers at runtime for this component and descendants (as far as they don't have providers for the same key already)

like demonstrated in

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I think the answer should split to 2, it's not clear, reading the question, if it refer to lazy-loading or just registering after bootstrap (i.e resolving injectors, setting Component.providers, etc) – Shlomi Assaf Jul 18 '16 at 16:58
  • 1
    Also, services can be added at any time to any component, the bootstrap providers which are static/app-wide/singleton/what-not are fixed, that's right. Again, the question is not clear enough – Shlomi Assaf Jul 18 '16 at 17:00
  • 1
    For components, lazy-loading is already here via the new new router. It also important to know that a component must be compiled and this depends on the compilation mode offline/runtime thus lazy-loading is the best practice. – Shlomi Assaf Jul 18 '16 at 17:01
  • Why do you think lazy loading is related to this? I'm also not sure what you mean by the previous comments. You can instantiate a service imperatively but for components and directives the providers can't be modified except for components that are created in a function (requires browser-dynamic-platform) and `ViewContainerRef.createComponent()` which allows to pass an injector which can be set up with a providers list before `createComponent` is called. – Günter Zöchbauer Jul 18 '16 at 17:04
  • This is why I say the question is not clear. You can extend after bootstrap if your service was compiled but not added to any injector but later added to a lazy loaded bundle. And yes, lazy loading is infect extending an angular application after it was bootstraped – Shlomi Assaf Jul 18 '16 at 17:05