Skahrz Skahrz - 11 months ago 85
Javascript Question

Angular 2 and ngmodule injector

NGmodule gives a way to organise our code in modules.

It also proposes to provides some services as a property of the module and I dont understand the way it works.

First does it mean that if I add a service in the provides property of a NGmodule, it will expose the service (meaning that I have to call the module inside of another one to use its services ) ?

And so, is there a NGmodule injector level ?

How Can I use a service outside the module box in another module ?

Answer Source

Providing a service in a modules means that the service will be instantiated and made available to all components, directives, and pipes that are part of the module. The word 'instantiation' is key here - since services are singletons, a module must keep track of services for every components, directive, or pipe that uses them. You could also provide the service in individual components, but that would instantiate the service each in each component, effectively negating the reason why we would use a singleton service in the first place. Providing it at the module-level solves this problem for us.

If you want to make your service available outside of your module, then don't have to do anything. Providing the service within a module that is imported in your project means that it's already available anywhere in your project.

Related: Why is a service provided in a feature module available everywhere?

If you wanted to make components, directives, or pipes available outside of your module, then you have to export them (and import them in the module where you want to use them). You can do that by using the export keyword in your module.

Related: What classes should I export?

For example, you can use the NgIf directive because it's exported from the CommonModule (docs), which we then import in our own modules:

  providers: [
    {provide: NgLocalization, useClass: NgLocaleLocalization},

Fun fact: if you only have one module (the root module that's bootstrapped), then you would actually only use the BrowserModule instead of the CommonModule. The reason all of the functionality of CommonModule is in BrowserModule is because BrowserModule just imports and the re-exports the entire CommonModule.

There's a great in-depth guide to the module system on angular2's website if you want more info. The FAQ page that I linked before is also super useful.