Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Dependency Injection in Angular 2 With ES5

4.83/5 (4 votes)
25 Feb 2016CPOL 6K  
Dependency Injection in Angular 2 With ES5

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.

JavaScript
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:

JavaScript
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 officially 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?

Dependency Injection in Angular 2 With ES5 was originally published by Dave Ceddia at Angularity on February 17, 2016.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)