Click here to Skip to main content
15,887,371 members
Articles / Programming Languages / Javascript

Dependency Injection in Angular 2 With ES5

Rate me:
Please Sign up or sign in to vote.
4.83/5 (4 votes)
25 Feb 2016CPOL 5.9K  
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.

This article was originally posted at https://daveceddia.com/feed.xml

License

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


Written By
United States United States
Dave is a Software Engineer in the Boston area and writes about AngularJS and other JavaScript things over at daveceddia.com

Comments and Discussions

 
-- There are no messages in this forum --