jdraper3
jdraper3

Reputation: 116

AngularJS and Typescript - Services injected into other services are undefined

I'm using this starter template with the modifications outlined in this SO post. It has been smooth sailing until now - I'm trying to inject a service into the constructor of another service, but the injected value is always 'undefined'. There are no errors thrown.

Here is a simplified example:

module app.services {
    export class dashboardFilterService implements IService {
        constructor($rootScope: ng.IRootScopeService) {
            // $rootScope is undefined...
            //$rootScope.$broadcast('FilterInitialized');
        }
    }
}
app.registerService('dashboardFilterService', ['$rootScope']);

Injecting services into controllers works fine. I am pretty new to typescript as well as angular, so this might be obvious to someone who has more experience with it. Here is the compiled js for reference:

var app;
(function (app) {
    (function (services) {
        var dashboardFilterService = (function () {
            function dashboardFilterService($rootScope) {
                // $rootScope is undefined...
                //$rootScope.$broadcast('FilterInitialized');
            }
            return dashboardFilterService;
        })();
        services.dashboardFilterService = dashboardFilterService;
    })(app.services || (app.services = {}));
    var services = app.services;
})(app || (app = {}));
app.registerService('dashboardFilterService', ['$rootScope']);

Upvotes: 3

Views: 8364

Answers (2)

basarat
basarat

Reputation: 276199

Recommended pattern:

module app.services {
    export class dashboardFilterService implements IService {
        static $inject = ['$rootScope']; // This should do it
        constructor($rootScope: ng.IRootScopeService) {
            //$rootScope.$broadcast('FilterInitialized');
        }
    }
    app.registerService('dashboardFilterService', dashboardFilterService );
}

PS: I did a video on the subject : http://www.youtube.com/watch?v=Yis8m3BdnEM&hd=1

Upvotes: 5

NicolasMoise
NicolasMoise

Reputation: 7279

Well I don't know typescript but the safest way to do dependency injection in javascript is

app.service('serviceName', ['$rootScope', 'anotherServ', function($rootScope, anotherService){

}]);

I think your not passing the service function as the last element in your array, so in your case, something like this:

app.registerService('dashboardFilterService', ['$rootScope', dashboardFilterService]);

Upvotes: 1

Related Questions