typescript 带有依赖注入和缩小的打字稿中的 Angular 服务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19269117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:51:38  来源:igfitidea点击:

Angular service in typescript with dependency injection and minification

angularjstypescriptminify

提问by Dreamwalker

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.

我现在正试图让我的头脑转过 angularjs。我目前正在查看服务,我也在使用打字稿进行代码。

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 $httpfrom 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.

现在,如果这被缩小,我会$http从构造函数中丢失,并且 angular 需要变量名。所以我检查了一下,发现我可以使用 $inject 而不是构造函数,但这也会遇到同样的缩小问题。

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.

人们如何在打字稿上下文中处理缩小和角度问题?我正在努力寻找一些关于如何处理的可靠文档。对我来说,在现代 api 中出现这些问题似乎很奇怪,所以我一定在某个地方遗漏了一些东西。

回答by basarat

Just using the $injectsyntax. e.g. :

只是使用$inject语法。例如:

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

PS:我做了一个关于这个主题的详细视频:http: //www.youtube.com/watch?v=WdtVn_8K17E& hd=1

回答by pcan

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.

目前,官方的 TypeScript 编译器仍然没有发出可以在运行时用于 DI 系统的接口元数据。有关于发射器可扩展性的问题在这里。与此同时,我创建了一个 AngularJS 1.3 应用程序的示例项目(以及一个定制版本的 TS 编译器,它发出接口元数据),该应用程序提供装饰器以在应用程序模块中注册组件并在运行时使用类元数据注入依赖项。你可以看看这里