Reader small image

You're reading from  Getting Started with Angular - Second edition - Second Edition

Product typeBook
Published inFeb 2017
Reading LevelIntermediate
PublisherPackt
ISBN-139781787125278
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Minko Gechev
Minko Gechev
author image
Minko Gechev

Minko Gechev is a software engineer who strongly believes in open source software. He has developed numerous such projects including codelyzer, the AngularJS style guide, aspect.js and many others, and is one of the coauthors of the official Angular style guide.
Read more about Minko Gechev

Right arrow

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 the benefits of the mentioned approach are:

  • We can easily pass different versions of the dependencies of the Car class for a testing environment, or for instantiating...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Getting Started with Angular - Second edition - Second Edition
Published in: Feb 2017Publisher: PacktISBN-13: 9781787125278

Author (1)

author image
Minko Gechev

Minko Gechev is a software engineer who strongly believes in open source software. He has developed numerous such projects including codelyzer, the AngularJS style guide, aspect.js and many others, and is one of the coauthors of the official Angular style guide.
Read more about Minko Gechev