Search code examples
javascriptangularecmascript-5

Correctly defining Angular 2.1.2 ES5 service for DI


I've defined an Angular 2 service that has the Http service injected into it and is used by other components, but I don't think I've done it correctly:

(function (app) {
'use strict';
app.LoaderService = ng.core.Component({
    providers: [ng.http.Http],
    // TODO We shouldn't need to define a template in a service. Maybe service shouldn't be a Component?
    template: ''
  }).Class({
    constructor: [ng.http.Http, function (http) {
        this.http = http;
    }],
    getData: function (url, target) {
        var getter = this.http.get(url);
        getter.subscribe(function (result) {
            target.data = result.json();
        });
    }
  });
})(window.app || (window.app = {}));

Whilst this works, using 'ng.core.Component' forces me to define a 'template', otherwise I get a 'No template specified' error, but it's really just a service, it shouldn't need a template.

I tried defining it using 'ng.core.Injectable().Class(...)' as in this question:

create an angular 2 service in es5

but that gives an error 'ng.core.Injectable(...).Class is not a function'. Maybe Angular has changed since that answer was written?

There are also plenty of examples of writing services as simple functions, but that wouldn't let me inject the Http service into it.

How should I define the service in pure Javascript to support both injecting Http into it and allowing it to be injected into Components?


Solution

  • Yes, there is no longer Class property.

    Source code from ng2 beta-5 looks like:

    TypeDecorator.annotations = chainAnnotation;
    TypeDecorator.Class = Class;
    if (chainFn) chainFn(TypeDecorator);
    return TypeDecorator;
    

    https://github.com/angular/angular/blob/2.0.0-beta.5/modules/angular2/src/core/util/decorators.ts#L247-L267

    Today you can just use ng.core.Class for your service. Here's cheatsheet

    And here's Plunker Example