앱 구성, angular.js의 사용자 지정 공급자 내에서 $ http 사용
주요 질문-가능합니까? 나는 운없이 시도했다 ..
메인 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
어떤 아이디어?
감사!
결론은 다음과 같습니다.
- 당신은 수없는 공급자 구성 섹션에 서비스를 주입 .
- 당신은 CAN 공급자의 서비스를 초기화하는 섹션으로 서비스를 주입 .
세부:
Angular 프레임 워크에는 2 단계 초기화 프로세스가 있습니다.
1 단계 : 구성
이 config
단계 동안 모든 공급자가 초기화되고 모든 config
섹션이 실행됩니다. config
섹션 제공자 객체를 구성하고, 따라서 그들이 제공 개체를 주입 할 수있는 코드를 포함 할 수있다. 그러나 공급자는 서비스 개체의 공장이고이 단계에서는 공급자가 완전히 초기화 / 구성되지 않았으므로이 단계에서 공급자 에게 서비스 생성을 요청할 수 없습니다.-> 구성 단계에서는 사용할 수 없습니다. 주입 서비스 . 이 단계가 완료되면 모든 공급자가 준비됩니다 (구성 단계가 완료된 후에는 공급자 구성을 더 이상 수행 할 수 없음).
2 단계 : 실행
run
단계 동안 모든 run
섹션이 실행됩니다. 이 단계 에서 공급자는 준비가되어 있으며 서비스를 만들 수 있습니다.-> run
단계에서 서비스를 사용 / 주입 할 수 있습니다 .
예 :
1. $http
공급자 초기화 기능에 서비스를 삽입하면 작동 하지 않습니다.
//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
오류가 발생합니다.
Uncaught Error: Unknown provider: $http from services
이 오류가 실제로 말하는 것은 서비스 $httpProvider
를 만드는 데 사용되는이 $http
아직 준비되지 않았다는 것입니다 (아직 config
단계 에 있기 때문에 ).
주수 2. $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;
};
});
Since we are now injecting the service into the service initialization function, which is executed during run
phase this code will work.
This might give you a little leverage:
var initInjector = angular.injector(['ng']);
var $http = initInjector.get('$http');
But be careful, the success/error callbacks might keep you in a race-condition between the app start and the server response.
This is an old question, seems we have some chicken egg thing going on if we want to rely on the core capability of the library.
Instead of solving the problem in a fundamental way, what I did is by-pass. Create a directive that wraps the whole body. Ex.
<body ng-app="app">
<div mc-body>
Hello World
</div>
</body>
Now mc-body
needs to be initialized before rendering (once), ex.
link: function(scope, element, attrs) {
Auth.login().then() ...
}
Auth
is a service or provider, ex.
.provider('Auth', function() {
... keep your auth configurations
return {
$get: function($http) {
return {
login: function() {
... do something about the http
}
}
}
}
})
Seems to me that I do have control on the order of the bootstrap, it is after the regular bootstrap resolves all provider configuration and then try to initialize mc-body
directive.
And this directive seems to me can be ahead of routing, because routing is also injected via a directive ex. <ui-route />
. But I can be wrong on this. Needs some more investigation.
In response to your question, "Any Ideas?", I would have respond with "yes". But wait, there's more!
I suggest just using JQuery in the config. For example:
var app = angular.module('myApp', ['services']);
app.config(['$anyProvider', function ($anyProvider) {
$.ajax({
url: 'www.something.com/api/lolol',
success: function (result) {
$anyProvider.doSomething(result);
}
});
}]);
'IT story' 카테고리의 다른 글
bash : mkvirtualenv : 명령을 찾을 수 없습니다. (0) | 2020.09.04 |
---|---|
HTML5 날짜 선택기에 대한 스타일 옵션이 있습니까? (0) | 2020.09.04 |
EC2 Elastic Load Balancer를 HTTP에서 HTTPS로 리디렉션 (0) | 2020.09.04 |
Python에서 매개 변수의 강제 이름 지정 (0) | 2020.09.04 |
Android-로그에 전체 예외 역 추적 인쇄 (0) | 2020.09.04 |