Angular service in typescript with dependency injection and minification

不羁的心 提交于 2019-12-22 03:40:29

问题


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.


回答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




回答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.



来源:https://stackoverflow.com/questions/19269117/angular-service-in-typescript-with-dependency-injection-and-minification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!