DI in Angular

Another way we can approach this is by taking advantage of the DI pattern. We're already familiar with it from AngularJS; let's demonstrate how we can refactor the preceding code using DI in the context of Angular:

class Engine {...} 
class Transmission {...} 
 
@Injectable() 
class Car { 
  engine; 
  transmission;
 
  constructor(engine: Engine, transmission: Transmission) { 
    this.engine = engine; 
    this.transmission = transmission; 
  } 
} 

All we did in the preceding snippet was add the @Injectable class decorator on top of the definition of the Car class and provide type annotations for the parameters of its constructor.

Benefits of DI

There is one more step left, which we'll take a look at in the next section. Before that, let's take a look at what ...

Get Getting Started with Angular - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.