3

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']);

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

1

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]);

1 Comment

The app.registerService helper function does actually pass the arguments that way, so I'm still not exactly sure why that method didn't work. Here is the code: export function registerService(className: string, services = []) { var service = className[0].toLowerCase() + className.slice(1); services.push(() => new app.services[className]()); angular.module('app.services').factory(service, services); }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.