Dependency Injection in Angular 2 With ES5

Dave Ceddia bio photo By Dave Ceddia Comment

Angular 2 w/ ES5

Writing Angular 2 in ES5, and trying to inject some dependencies? It actually works a lot like Angular 1.

Anything you’re injecting needs to be added to the providers or viewProviders array (for more on the difference between those, see here).

After that, pass an array as the constructor: where the last item is the constructor function itself, and all previous items are the services to inject. This is just like Angular 1’s dependency injection syntax.

var MyService =
  ng.core
  .Class({
    constructor: function() {},
    getName: function() {
      return "Angular 2";
    }
  });

var HelloApp =
  ng.core
  .Component({
    selector: 'hello-app',
    template: '<h1>Hello {{name}}!</h1>',
    viewProviders: [MyService]
  })
  .Class({
    constructor: [MyService, function(myService) {
      this.name = myService.getName();
       console.log(myService.getName());
    }]
  });

(Angular 2 example in plunker)

Here’s the equivalent code in Angular 1:

var app = angular.module('demo', []);

app.factory('MyService', function() {
  return {
    getName: getName
  };
  
  function getName() {
    return "Angular 1";
  }
});

app.directive('helloApp', ['MyService', function(myService) {
  return {
    restrict: 'E',
    template: '<h1>Hello {{ctrl.name}}!</h1>',
    controllerAs: 'ctrl',
    controller: function() {
      this.name = myService.getName();
    }
  };
}]);

(Angular 1 example in plunker)

ES5?

Angular 2’s ES5 syntax isn’t all that foreign coming from Angular 1. It eases the learning curve a bit.

However, even though ES5 and ES6 (and even Dart) are offically supported languages for Angular 2, right now the community seems to be favoring TypeScript – which means ES5/ES6 help might be harder to come by.

What do you think? Is TypeScript the way of the future? Or do you have more of an “over my dead body” feeling toward types?

comments powered by Disqus