Chapter 4. Dependency injection

 

This chapter covers

  • Introducing Dependency Injection (DI) as a design pattern
  • Benefits of DI
  • How Angular implements DI
  • Registering object providers and using injectors
  • The hierarchy of injectors
  • Applying DI in the online auction application

In the previous chapter, we discussed the router, and now your online auction application knows how to navigate from the Home view to an almost-empty Product Details view. In this chapter, you’ll continue working on the online auction, but this time we’ll concentrate on how to use Angular to automate the process of creating objects and assembling the application from its building blocks.

Any Angular application is a collection of components, directives, and classes that may depend on each other. Although each component can explicitly instantiate its dependencies, Angular can do this job using its dependency injection (DI) mechanism.

We’ll start this chapter by identifying the problem that DI solves and reviewing the benefits of DI as a software engineering design pattern. Then we’ll go over the specifics of how Angular implements the DI pattern using an example ProductComponent that depends on a ProductService. You’ll see how to write an injectable service and how to inject it into another component.

4.1. The Dependency Injection and Inversion of Control patterns

4.2. Injectors and providers

4.3. A sample application with Angular DI

4.4. Switching injectables made easy

4.5. The hierarchy of injectors

4.6. Hands-on: using DI in the online auction application

4.7. Summary