Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']);
like image 244
jdraper3 Avatar asked Dec 28 '25 19:12

jdraper3


1 Answers

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

like image 180
basarat Avatar answered Dec 31 '25 10:12

basarat