DEV Community

Aviv Ben-Yosef
Aviv Ben-Yosef

Posted on • Originally published at codelord.net

Angular Dependency Injection Annotations With ES6 Classes

After covering how ES6 classes can be used for defining services in Angular in the previous post, I was asked how do these play along with Angular’s dependency injection annotations.

To recap, dependency injection annotations are used so that Angular would know what it should be injecting even when code is obfuscated/minified.
This is a regular service with injection in ES5:

    angular.module('app').service('Service', function($http) {
      this.get = function() { ... };
    });
Enter fullscreen mode Exit fullscreen mode

And that example with explicit annotations would look like so:

    angular.module('app').service('Service', ['$http', function($http) {
      this.get = function() { ... };
    }]);
Enter fullscreen mode Exit fullscreen mode

How does this play along with ES6 classes?

The above example as a class looks like this:

    angular.module('app').service('Service', Service);

    class Service {
      constructor($http) {
        this.$http = $http;
      }
      get() { ... }
    }
Enter fullscreen mode Exit fullscreen mode

And in order to add proper annotations to it, simply add this line at the bottom:

    Service.$inject = ['$http'];
Enter fullscreen mode Exit fullscreen mode

That’s all there’s to it, if you insist on adding these manually.

But please, stop doing it like an animal, and incorporate something like ng-annotate.
Given that you’re using ES6, you very likely already transpiling your code into ES5, and ng-annotate can simply go over your code at that point and add these as necessary.

Keep it classy! </dadpun>

Top comments (0)