2

I try to implement a provider with TypeScript that has dependencies to services. I think I have to inject those services into the get function, but how is this done in TypeScript?

In JavaScript it is implemented like this:

angular.module('HTML5Shell.Services')
.provider('service', [
    'baseService',
    function (baseService) {

        return {
            $get: ['$rootScope',
                function ($rootScope) {

                    return {
                        method: function (param) {
                            return 'method called';
                        }
                    };
            }]
        };
    }]);

1 Answer 1

5

I found the solution - maybe it is the desired solution to implement a provider, except using any ;-)

module services {
    'use strict';

export class Service {

        private $rootScope:any;

        public start($rootScope:any) {
            this.$rootScope = $rootScope;
        }

        public serviceMethod() {
            this.$rootScope ...
        }
}

export class ServiceProvider implements ng.IServiceProvider {

        static $inject = ['baseService'];

        constructor(private baseService:any) {
        }

        $get = ['$rootScope', ($rootScope:any) => {
                var translationService = new Service();
                translationService.start($rootScope);
                return translationService;
            }];

        public configure = () => {
            this.baseService.method();
        }
}

    angular
        .module('Module')
        .provider('service', ServiceProvider);
}
Sign up to request clarification or add additional context in comments.

1 Comment

With that solution you get a new instance for every injection because of the new Service();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.