Chapter 5. Dependency injection in Angular

 

This chapter covers

  • Introducing dependency injection as a design pattern
  • Understanding how Angular implements DI
  • Registering object providers and using injectors
  • Adding Angular Material UI components to ngAuction

Chapter 4 discussed the router, and now the ngAuction app knows how to navigate from the home view to the product-detail view. In this chapter, we’ll concentrate on how Angular automates the process of creating objects and assembling the application from its building blocks.

An Angular application is a collection of components, directives, and services 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.

After that, you’ll see a sample application that demonstrates how Angular DI allows you to easily replace one component dependency with another by changing just one line of code. At the end of the chapter, we’ll go through a hands-on exercise to build the next version of ngAuction, which uses Angular Material UI components.

5.1. The dependency injection pattern

5.2. Benefits of DI in Angular apps

5.3. Injectors and providers

5.4. A simple app with Angular DI

5.5. Switching injectables made easy

5.6. Declaring providers with useFactory and useValue

5.7. Providers in lazy-loaded modules

5.8. Providers in eagerly loaded modules

5.9. Hands-on: Using Angular Material components in ngAuction

Summary

sitemap