如何在AngularJs中设置来自其提供商的服务的依赖关系

How to set the dependencies of a service from its provider in AngularJs?

本文关键字:提供商 服务 关系 依赖 AngularJs 设置      更新时间:2023-09-26

我正在尝试执行以下操作:

var myApp = angular.module('myApp', []);
myApp.provider('routeResolver', ['$q','$rootScope',function($q, $rootScope)
    {        
        console.log( $q, $rootScope );
        this.$get = function()
        {
            return this;
        }
    }]
);

然而,这会产生错误:Unknown Provider $q

所以我把代码改为:

myApp.provider('routeResolver', ['$qProvider','$rootScopeProvider',function($q, $rootScope)
    {        
        console.log( $q.defer() );
        console.log( $rootScope );
        this.$get = function()
        {
            return this;
        }
    }]
);

然而,这给出了CCD_ 2的误差。甚至做:

console.log( $q.$get().defer() );

不起作用。有什么想法吗?

代替:

this.$get = function()
  {
    return this;
  }

试试这个:

return {
  // object being returned has to implement $get method
  $get: function() {
    // you should be able to use $q and $rootScope here
    return this;
  }
};

除了$get,还应该有其他方法可以访问所有注入的服务:

return {
  // object being returned has to implement $get method
  $get: function() {
    // you should be able to use $q and $rootScope here
    return this;
  },
  // you can also have more methods here
  someOtherMethod: function() {
    // you should be able to use $q and $rootScope here as well
    // for example:
    $rootScope.$apply();
  }
};

这是假设您将$q$rootScope注入构造函数(无论您是否使用数组表示法)。

这就是我从这里和这里推断出的