使用TypeScript在AngularJS中实现Provider

时间:2015-08-17 12:06:20

标签: typescript

我尝试使用具有服务依赖性的TypeScript实现提供程序。我想我必须将这些服务注入到get函数中,但是如何在TypeScript中完成?

在JavaScript中,它实现如下:

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

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

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

1 个答案:

答案 0 :(得分:4)

我找到了解决方案 - 也许它是实现提供者所需的解决方案,除了使用任何; - )

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