Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 injector hierarchy and NgModule

I wonder how NgModule actually affects Angular 2 injector hierarchy.

What does the hierarchy look like in an app with nested modules? Does it create a new injector instance per each module or gets access to top-level injector (similarly to Angular 1.x modules)?

It can be somewhat confusing to figure out the tree in a big app.

Is there a way to print out, inspect or explore visually the hierarchy of injectors (like it could be done for scope hierarchy in Angular 1.x)?

like image 993
Estus Flask Avatar asked Aug 19 '16 04:08

Estus Flask


People also ask

What is hierarchical dependency injection Angular 2?

A hierarchical dependency injection system allows us to define different boundaries or scopes for our dependencies to run in and follows the component tree structure. By default, services registered to Angular are application wide but we can also create services that are isolated to a subset of components.

What is NgModule Angular?

@NgModule takes a metadata object that describes how to compile a component's template and how to create an injector at runtime. It identifies the module's own components, directives, and pipes, making some of them public, through the exports property, so that external components can use them.

What is difference between @inject and @injectable in Angular?

The @Injectable decorator aims to actually set some metadata about which dependencies to inject into the constructor of the associated class. It's a class decorator that doesn't require parameters. Without this decorator no dependency will be injected...


1 Answers

According to the Modules documentation: https://angular.io/docs/ts/latest/guide/ngmodule.html

Angular registers these providers with the root injector of the module's execution context. That's the application's root injector for all modules loaded when the application starts.

Angular can inject one of these provider services into any component in the application. If this module provides the HeroService, or any module loaded at launch provides the HeroService, Angular can inject the same HeroService intance into any app component.

A lazy loaded module has its own sub-root injector which typically is a direct child of the application root injector.

Lazy loaded services are scoped to the lazy module's injector. If a lazy loaded module also provides the HeroService, any component created within that module's context (e.g., by router navigation) gets the local instance of the service, not the instance in the root application injector.

Components in external modules continue to receive the instance created for the application root.

So, you have one injector that is shared between all the modules. However, lazy-loaded components will have a child injector

like image 93
AbdulRahman AlHamali Avatar answered Sep 20 '22 11:09

AbdulRahman AlHamali