Dependency Injection in Angular 2 With ES5

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 =
    constructor: function() {},
    getName: function() {
      return "Angular 2";

var HelloApp =
    selector: 'hello-app',
    template: '<h1>Hello {{name}}!</h1>',
    viewProviders: [MyService]
    constructor: [MyService, function(myService) { = 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 {{}}!</h1>',
    controllerAs: 'ctrl',
    controller: function() { = myService.getName();

(Angular 1 example in plunker)


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?

Learning React can be a struggle -- so many libraries and tools!
My advice? Ignore all of them :)
For a step-by-step approach, read my book Pure React.

Loved it! Very well written and put together. Love that you focused only on React. Wish I had stumbled onto your book first before I messed around with all those scary "boilerplate" projects.
— John Lyon-Smith
comments powered by Disqus