Table of Contents Preface typescript angular

Dependency Injection

Since we are cod­ing in Type­Script and make heavy use of the class syn­tax, we can not use au­to­mated an­no­ta­tions tools, such as ng-annotate[1]. Man­u­ally adding de­pen­dency in­jec­tion can be done by adding a sta­tic prop­erty called $inject to our classes (see snip­pet be­low), which would con­form the An­gu­lar 1.x de­pen­ceny in­jec­tion an­no­ta­tion.[2]

class MarvelApiService {
    public static $inject = ['$http', '$q'];

    constructor(
        private $http::ng.IHttpService
        private $q: ng.IQService
    ) {
        // Code goes here
    }
}

Us­ing dec­o­ra­tors is an­other more de­clar­a­tive way of adding de­pen­dency in­jec­tion to your classes (for an in­tro­duc­tion of dec­o­ra­tors see the Type­Script sec­tion). Be­cause we want to dec­o­rate classes and their meth­ods we have to con­form both the ClassDecorator and MethodDecorator in­ter­face. The be­low code snip­pet is an ex­am­ple im­ple­men­ta­tion.

export function inject (...dependencies:string[]) {
    return function decorator (
        target:Function,
        key?:string|symbol,
        descriptor?:TypedPropertyDescriptor<any>
    ) {
        // If "descriptor" decorate
        // -> class method, otherwhise
        // -> class
        var receiver = descriptor ? descriptor.value : target;
        receiver.$inject = dependencies;
    }
}

In­ject­ing de­pen­den­cies can then be done by sim­ply prepend­ing a class or a class method with @inject. The dec­o­ra­tor ac­cepts any num­ber of string ar­gu­ments. In­ject­ing the MarvelApiService would look like this:

impport { inject } from 'utils/decorators';

@inject('$http', '$q')
class MarvelApiService {
    constructor(
        private $http::ng.IHttpService
        private $q: ng.IQService
    ) {
        // Code goes here
    }
}

It may not look like a big im­prove­ment ofer the static prop­erty syn­tax, but you’ll no­tice it when you have mulit­ple func­tions with mul­ti­ple de­pen­den­cies.


  1. ng-anotate on Github

  2. Angular Documentation - Dependency Injection