1

I was having trouble injecting a service into a component using ES5. I was finally able to get it to work, but discovered a couple different ways a service can be declared. Are one of these the more "Angular" way to declare a service?

Here is the component

(function (app) {
app.employeeSearchComponent = ng.core
    .Component({
        selector: 'employee-search',
        templateUrl: rootUrl + 'Home/EmployeeSearch',
        providers: [app.Service]
    })
    .Class({
        constructor: [app.Service, function(service) {
                   console.log(service.greeting);
            }]
        });
})(window.app || (window.app = {}));

Here is the service (Option 1)

(function(app) {
    app.Service = ng.core.Class({
        constructor: function(){},
        greeting: function() {
            return 'hello';
        }
    });
})(window.app || (window.app = {}));

Here is the service (Option 2)

(function(app) {
    app.Service = function() {
        this.greeting = function() {
            return 'hello';
        }
    };
})(window.app || (window.app = {}));
puddinman13
  • 1,408
  • 4
  • 18
  • 35
  • Looks similar to http://stackoverflow.com/questions/34532138/how-to-inject-custom-service-to-angular-component-in-plain-es5-javascript – Günter Zöchbauer Jan 04 '16 at 19:53
  • 1
    You are correct. The outcome and code are very similar. However, I am looking for an explanation as to which version of the service is preferred... which the url you provided does not explain. – puddinman13 Jan 04 '16 at 19:55
  • @puddinman13 I think your answer may be [here](https://github.com/angular/angular/blob/master/modules/angular2/src/core/util/decorators.ts#L128) – Eric Martinez Jan 04 '16 at 21:37

2 Answers2

2

I think you will be good with option 1. Find an example from Angular.io cheat sheet

var OtherService = ng.core.Class({constructor: function() { }});
Omasiri
  • 116
  • 1
  • 3
0

Going with first option you could probably declare dependencies to other services, like ng.http, in second you cant do that easily.