简体   繁体   English

使用$ inject的angularjs服务?

[英]angularjs services using $inject?

(function() {
    angular.module('MyApp')
        .factory('Contact', Contact);

    Contact.$inject = ['$http'];

    function Contact($http) {
        return {
            send: function(data) {
                return $http.post('/contact', data);
            }
        };
    }
})();

In a boilerplate I found above code. 我在上面的代码中找到了样板文件。 I have few confusions : 我很少有困惑:

  1. why not just inject $http like this 为什么不直接注入这样的$http

    angular.module('MyApp').factory('Contact', function($http){ });

  2. is it necessary to put the service within self-execution function? 是否有必要将服务置于自执行功能之内?

First - The problem will arise when you try to minimize your angular files. 首先 - 当您尝试最小化角度文件时,会出现问题。 Your minimizer may convert $http to variable b and their identity will still be preserved in the strings if you use $inject otherwise you will have errors. 你的最小化器可能会将$ http转换为变量b,如果你使用$inject ,它们的身份仍会保留在字符串中,否则你会有错误。

Second - When you are using self-executed functions, you are isolating the scope of your services. 第二 - 当您使用自执行功能时,您正在隔离服务范围。 That will help when you combine all the files into one. 当您将所有文件合并为一个文件时,这将有所帮助。 If you don't do that variables or functions with the same name will produce errors. 如果不这样做,那么具有相同名称的变量或函数将产生错误。

This is explained in more detail in John Papa's styleguide 这在John Papa的风格指南中有更详细的解释

Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM