Modules are a nice mechanism to create libraries that you can reuse in multiple applications. These libraries can contain components, pipes, directives, services or any other Angular 2 element. The concept remembers me the old Angular 1.x modules. Inside a module, you can define a list of elements that will be injectable inside other modules, without having to specify
directives inside a
Component. This is because modules expose these elements to our application’s root injector, so the effect is the same as
provide declaration in rc4 and earlier versions.
And I have made a little app to test them. You can play with it here. I’ve extended the base Angular 2 plunker to create a new service, called
SimpleService. Instead of being on
app directory, it’s located on the
Then I’ve created a Module called
SimpleServiceModule. Its only responsibility is to make avalable the
SimpleService to other modules:
I want to inject the
SimpleService in my
AppComponent. For that, instead of using the providers property in my
ComponentMetadata object, I will import it into my
Look! There’s also a
BrowserModule import! Well, some of Angular 2 components have been already refactored into components, like the
BrowserModule or the
Now I can inject the
SimpleService into my
AppComponent with no problems:
Despite it’s a very simple example, with this introduction you can see how you can create modules and use them in other modules.
Hope this article has been useful to you.