Kos*_*ika 90 javascript angularjs angular-services
主要问题 - 有可能吗?我试着没有运气..
主app.js
...
var app = angular.module('myApp', ['services']);
app.config(['customProvider', function (customProvider) {
}]);
...
Run Code Online (Sandbox Code Playgroud)
提供者本身
var services = angular.module('services', []);
services.provider('custom', function ($http) {
});
Run Code Online (Sandbox Code Playgroud)
我有这样的错误:
Uncaught Error: Unknown provider: $http from services
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
谢谢!
Dan*_*lev 158
Angular框架有一个2阶段初始化过程:
在此config阶段期间,将初始化所有提供程序并config执行所有部分.这些config部分可能包含配置提供程序对象的代码,因此可以使用提供程序对象注入它们.但是,由于提供程序是服务对象的工厂,并且在此阶段提供程序未完全初始化/配置 - > 您不能要求提供程序在此阶段为您创建服务 - >在配置阶段您不能使用/注入服务.完成此阶段后,所有提供程序都已准备就绪(配置阶段完成后无法再进行提供程序配置).
在run阶段期间run,执行所有部分.在此阶段,提供商已做好准备并可以创建服务 - >在run阶段期间您可以使用/注入服务.
$http服务注入提供程序初始化函数将不起作用Run Code Online (Sandbox Code Playgroud)//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服务注入到在config阶段执行的函数中,我们将得到一个错误:
Run Code Online (Sandbox Code Playgroud)Uncaught Error: Unknown provider: $http from services
这个错误实际上说的$httpProvider是用于创建$http服务的那个还没有准备好(因为我们还处于config阶段).
$http服务注入服务初始化函数将起作用://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;
};
});
Run Code Online (Sandbox Code Playgroud)
由于我们现在将服务注入到服务初始化函数中,该函数在run阶段期间执行,因此该代码将起作用.
Cod*_*ody 63
这可能会给你一点杠杆:
var initInjector = angular.injector(['ng']);
var $http = initInjector.get('$http');
Run Code Online (Sandbox Code Playgroud)
但要小心,成功/错误回调可能会让您处于应用程序启动和服务器响应之间的竞争状态.
| 归档时间: |
|
| 查看次数: |
61648 次 |
| 最近记录: |