简体   繁体   中英

injecting dependency through factory in AngularJs

I have below service code

(function () {
    'use strict';

    angular.module('App')
           .factory('apiservice', apiservice);

    /* @ngInject */
    function apiservice($http) {
        var service = {
            getData: getGridData,
        };

        return service;

       //code ommitted for clarity
    }
})();

When I minifying and bundling, the dependency is getting screwed up. So I wanted to change $scope to '$scope' so minifier won't mess up with name.

I know there are several ways to do it. But can I make it work like below:

(function () {
    'use strict';

    angular.module('App')
           .factory('apiservice', ['http', apiservice]);

    function apiservice($http) {
        return service;
    }
})();

Any help is appreciated.

You have a couple of options,. the first is to use the extended syntax for dependency injection. In this case:

.factory('apiservice', ['$http', apiservice]);

function apiservice($http) {
  return service;
}

This can also be written as:

.factory('apiservice', apiservice);

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

function apiservice($http) {
  return service;
}

Or put add another build step before you minify, such as ng-annotate which will convert your syntax to the extended version.

A factory like this

.factory('apiservice', function($http) {
  return service;
});

Would become:

.factory('apiservice', ['$http', function($http) {
  return service;
});

Which would be safe to minify.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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