Angular service in typescript with dependency injection and minification

All we need is an easy explanation of the problem, so here it is.

I am trying to get my head round angularjs at the moment. I am currently looking at services I am also using typescript for code.

Now from samples on the web I have seen that people use something like below for a service in typescript.

class Service
{
    constructor( private $http: ng.IHttpService )
    {
    }

    public MyMethod()
    {
        this.$http.get( "/" )
            .success( null )
            .error( null );
    }
}

Now if this is minified I would lose $http from the constructor and angular requires the variable names. So I checked around and found I can use $inject instead of the constructor but this also would get the same minification problem.

How are people dealing with minification and angular in a typescript context? I am struggling to find some solid docs on how this should be handled. To me this seems odd to have these problems in a modern api so I must be missing something somewhere.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Just using the $inject syntax. e.g. :

class Service
{
    static $inject = ['$http'];    
    constructor( private $http: ng.IHttpService )
    {
    }

    public MyMethod()
    {
        this.$http.get( "/" )
            .success( null )
            .error( null );
    }
}

PS: I did a detailed video on the subject : http://www.youtube.com/watch?v=WdtVn_8K17E&hd=1

Method 2

Currently the official TypeScript compiler still does not emit interface metadata that could be used at runtime for a DI system. There is an issue about the Emitter extensibility here.
In the meantime I have created a sample project (along with a customized version of the TS compiler that emits interface metadata) of an AngularJS 1.3 application that provides Decorators to register components in the application module and inject dependencies using class metadata at runtime. You can give a look here.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply