javascript - 在应用程序配置 angular.js 的自定义提供程序中使用 $http

标签 javascript angularjs angular-services

主要问题 - 这可能吗?我试过没有运气..

主 app.js

...
var app = angular.module('myApp', ['services']);
app.config(['customProvider', function (customProvider) {

}]);
...

提供商本身

var services = angular.module('services', []);
services.provider('custom', function ($http) {
});

我有这样的错误:

Uncaught Error: Unknown provider: $http from services 

有什么想法吗?

谢谢!

最佳答案

底线是:

  • 不能将服务注入(inject)提供商配置部分
  • 可以将服务注入(inject)初始化提供商服务的部分

详情:

Angular 框架有两个阶段的初始化过程:

阶段 1:配置

config 阶段,所有的提供者都被初始化,所有的 config 部分都被执行。 config 部分可能包含配置提供者对象的代码,因此它们可以注入(inject)提供者对象。 但是,由于提供者是服务对象的工厂,并且在这个阶段提供者没有完全初始化/配置 -> 你不能要求提供者在这个阶段为你创建服务 -> 在配置阶段你不能使用/注入(inject)服务。 完成此阶段后,所有提供程序都准备就绪(配置阶段完成后无法再进行提供程序配置)。

阶段 2:运行

run 阶段,所有 run 部分都被执行。在此阶段,提供商已准备就绪并可以创建服务 -> 在运行阶段,您可以使用/注入(inject)服务

例子:

1。将 $http 服务注入(inject)提供者初始化函数不会工作

//ERRONEOUS
angular.module('myModule').provider('myProvider', function($http) {
    // SECTION 1: code to initialize/configure the PROVIDER goes here (executed during `config` phase)
    ...

    this.$get = function() {
        // code to initialize/configure the SERVICE goes here (executed during `run` stage)

        return myService;
    };
});

由于我们试图将 $http 服务注入(inject)到一个在 config 阶段执行的函数中,我们将得到一个错误:

Uncaught Error: Unknown provider: $http from services 

这个错误实际上是说用于创建 $http 服务的 $httpProvider 还没有准备好(因为我们还在 config 阶段)。

2。将 $http 服务注入(inject)服务初始化函数将会工作:

//OK
angular.module('myModule').provider('myProvider', function() {
    // SECTION 1: code to initialize/configure the PROVIDER goes here (executed during `config` phase)
    ...

    this.$get = function($http) {
        // code to initialize/configure the SERVICE goes here (executed during `run` stage)

        return myService;
    };
});

由于我们现在将服务注入(inject)服务初始化函数,该函数在 run 阶段执行,此代码将起作用。

关于javascript - 在应用程序配置 angular.js 的自定义提供程序中使用 $http,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17497006/

相关文章:

Angular:使用 RxJs/BehaviorSubject 在组件之间动态共享数据

javascript - 自定义 jQuery 模糊函数在点击事件之前触发

javascript - 在momentjs中大写月份名称

JavaScript/Node + cURL

javascript - 工厂方法不返回 - TypeError : Cannot read property 'then' of undefined

javascript - 在 ONSEN 页面中启用 Angular JS

javascript - 使用前如何唤醒 Controller ?

javascript - 如何在 angular js 中的服务内创建指令?

javascript - Angular v4 : Do we store data in a Service or the Component or both?

javascript - jQuery - 如何检查页面上可用的 javascript?