How to inject dependencies into a provider using Angularjs?

前端 未结 5 1717
谎友^
谎友^ 2020-12-29 03:00

Is it possible to do DI in a provider method?

In this example

angular.module(\'greet\',[])
.provider(\'greeter\',function() {

  this.$get=function()         


        
5条回答
  •  南笙
    南笙 (楼主)
    2020-12-29 03:24

    Following up on IgrCndd's answer, here's a pattern that might avoid potential nastiness:

    angular.module('greet',[]).provider('greeter', function() {
    
        var $http;
    
        function logIt() {
            console.log($http);
        }
    
        this.$get = ['$http', function(_$http_) {
            $http = _$http_;
    
            return {
                logIt: logIt
            };
        }];
    });
    

    Note how similar this is to the equivalent service, making conversion between the two less troublesome:

    angular.module('greet',[]).factory('greeter', ['$http', function($http) {
    
        function logIt() {
            console.log($http);
        }
    
        return {
            logIt: logIt
        };
    });
    

提交回复
热议问题