Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make angular provider written in typescript minification safe

I have written an angular provider that needs $injector service to be injected in the $get function but I do not know how to write this in typescript and make it minification safe. Something like static $injector = ['']; notation that works for services and controllers.

Typescript:

export class ApiProvider implements IApiProvider {
    private baseRoute: string = '';
    private endpoints: { [name: string]: IApiEndPointConfig };

    static $inject = ['$injector']; //THIS DOES NOT WORK FOR PROVIDERS
    constructor() {
        this.baseRoute = '';
        this.endpoints = {};
    }

            // MORE CODE

    $get = ($injector: ng.auto.IInjectorService): { [name: string]: ApiEndpoint } => {
        var api: { [name: string]: ApiEndpoint } = {};
        var self:ApiProvider = this;
        angular.forEach(this.endpoints, (endpointConfig, name) => {
            api[name] = $injector.instantiate(ApiEndpoint, {
                baseRoute: self.baseRoute,
                endpointConfig: endpointConfig
            });
        });

        return api;
    };
}

The generated javascript for the $get function is:

this.$get = function ($injector) {
    var api = {};
    var self = _this;
    angular.forEach(_this.endpoints, function (endpointConfig, name) {
        api[name] = $injector.instantiate(Model.ApiEndpoint, {
            baseRoute: self.baseRoute,
            endpointConfig: endpointConfig
        });
    });

    return api;
};

And what I want it to be is something like:

this.$get = ['$injector', function ($injector) {
    var api = {};
    var self = _this;
    angular.forEach(_this.endpoints, function (endpointConfig, name) {
        api[name] = $injector.instantiate(Model.ApiEndpoint, {
            baseRoute: self.baseRoute,
            endpointConfig: endpointConfig
        });
    });

    return api;
}];
like image 503
masimplo Avatar asked May 27 '14 08:05

masimplo


1 Answers

I think I got it. After reading the $injector documentation more closely I found that the $inject string array notation can be used on any function. Thus I did something like:

constructor(){
   this.$get.$inject = ['$injector'];
}

$get = ($injector: ng.auto.IInjectorService): { [name: string]: ApiEndpoint } => {
    //using $injector
};

which produces:

this.$get = function ($injector) {
   //using $injector                    
};

this.$get.$inject = ['$injector'];
like image 83
masimplo Avatar answered Oct 02 '22 17:10

masimplo