Building  Large-Scale Web Applications with Angular
上QQ阅读APP看书,第一时间看更新

Comprehending Angular modules

In Angular, modules are a way to organize code into chunks that belong together and work as a cohesive unit. Modules are Angular's way of grouping and organizing code.

An Angular module primarily defines:

  • The components/directives/pipes it owns
  • The components/directives/pipes it makes public for other modules to consume
  • Other modules that it depends on
  • Services that the module wants to make available application-wide

Any decent-sized Angular app will have modules interlinked with each other: some modules consuming artifacts from other, some providing artifacts to others, and some modules doing both.

As a standard practice, module segregation is feature-based. One divides the app into features or subfeatures (for large features) and modules are created for each of the features. Even the framework adheres to this guideline as all of the framework constructs are divided across modules:

  • There is CommonModule that aggregates the standard framework constructs used in every browser-based Angular app
  • There is RouterModule if we want to use the Angular routing framework
  • There is HtppModule if our app needs to communicate with the server over HTTP

Angular modules are created by applying the @NgModule decorator to a TypeScript class. The decorator definition exposes enough metadata, allowing Angular to load everything the module refers to.

The decorator has multiple attributes that allow us to define:

  • External dependencies (using imports).
  • Module artifacts (using declarations).
  • Module exports (using exports).
  • The services defined inside the module that need to be registered globally (using providers).
  • The main application view, called the root component, which hosts all other app views. Only the root module should set this using the bootstrap property.

This diagram highlights the internals of a module and how they link to each other:

Modules defined in the context of Angular (using the  @NgModule decorator) are different from modules we import using the import statement in our TypeScript file. Modules imported through the  import statement are JavaScript modules, which can be in different formats adhering to CommonJS, AMD, or ES2015 specifications, whereas Angular modules are constructs used by Angular to segregate and organize its artifacts. Unless the context of the discussion is specifically a JavaScript module, any reference to module implies an Angular module. We can learn more about this here:  http://bit.ly/ng2be6-module-vs-ngmodule.

We hope one thing is clear from all this discussion: creating a single application-wide module is not the right use of Angular modules unless you are building something rudimentary.

It's time to get into the thick of the action; let's build our first component.