앱 시작 시 AngularJS 로드 구성
Angular에 구성 파일(JSON 형식)을 로드해야 합니다.모든 API 호출에서 사용되는 몇 가지 파라미터를 로드하기 위해 JS 앱을 시작합니다.그래서 Angular에서 할 수 있는지 궁금합니다.JS 및 설정 파일을 로드하는 장소/언제입니까?
주의: 구성 파일 파라미터를 서비스에 저장해야 하므로 컨트롤러가 로드되기 전에 json 파일 콘텐츠를 로드해야 합니다.서비스 유닛을 사용할 수 있습니다.이 경우 외부 json 파일을 사용하는 것은 필수입니다.앱 클라이언트는 외부 파일에서 앱 구성을 쉽게 업데이트할 수 있어야 하기 때문입니다.앱 소스를 통해.
편집필
파라미터를 사용하여 서비스를 설정하려고 하는 것처럼 들립니다.외부 설정 파일을 비동기적으로 로드하려면 자동 부스트랩을 사용하는 대신 데이터 로드 완료 콜백 내에서 각도 애플리케이션을 직접 부트스트랩해야 합니다.
서비스 URL이 실제로 정의되어 있지 않은 서비스 정의의 경우 이 예를 고려하십시오(이 예에서는 다음과 같습니다).contact-service.js):
angular.module('myApp').provider('contactsService', function () {
var options = {
svcUrl: null,
apiKey: null,
};
this.config = function (opt) {
angular.extend(options, opt);
};
this.$get = ['$http', function ($http) {
if(!options.svcUrl || !options.apiKey) {
throw new Error('Service URL and API Key must be configured.');
}
function onContactsLoadComplete(data) {
svc.contacts = data.contacts;
svc.isAdmin = data.isAdmin || false;
}
var svc = {
isAdmin: false,
contacts: null,
loadData: function () {
return $http.get(options.svcUrl).success(onContactsLoadComplete);
}
};
return svc;
}];
});
그런 다음 문서 준비 시 (이 경우 jQuery를 사용하여) 컨피규레이션파일을 로드하기 위한 콜을 발신합니다.그런 다음 콜백에서 로드된 json 데이터를 사용하여 angular app .config를 수행합니다..config 실행 후 응용 프로그램을 수동으로 부트스트랩합니다.매우 중요: 이 방법을 사용하는 경우 ng-app 지시문을 사용하지 마십시오. 그렇지 않으면 angular가 부트스트랩 자체를 수행합니다.자세한 내용은 다음 URL을 참조하십시오.
http://docs.angularjs.org/guide/bootstrap
다음과 같은 경우:
angular.element(document).ready(function () {
$.get('/js/config/myconfig.json', function (data) {
angular.module('myApp').config(['contactsServiceProvider', function (contactsServiceProvider) {
contactsServiceProvider.config({
svcUrl: data.svcUrl,
apiKey: data.apiKey
});
}]);
angular.bootstrap(document, ['myApp']);
});
});
업데이트: 다음은 JSFiddle의 예입니다.http://jsfiddle.net/e8tEX/
나는 키스 모리스가 제안한 접근 방식을 이해할 수 없었다.
그래서 config.js 파일을 생성하여 index.html에 포함시켰습니다.
config.discloss 。
var configData = {
url:"http://api.mydomain-staging.com",
foo:"bar"
}
index.displaces를 표시합니다.
...
<script type="text/javascript" src="config.js"></script>
<!-- compiled JavaScript --><% scripts.forEach( function ( file ) { %>
<script type="text/javascript" src="<%= file %>"></script><% }); %>
그런 다음 실행 함수에서 구성 변수를 $rootScope로 설정합니다.
.run( function run($rootScope) {
$rootScope.url = configData.url;
$rootScope.foo = configData.foo;
...
})
다음과 같은 경우에 상수를 사용할 수 있습니다.
angular.module('myApp', [])
// constants work
//.constant('API_BASE', 'http://localhost:3000/')
.constant('API_BASE', 'http://myapp.production.com/')
//or you can use services
.service('urls',function(productName){ this.apiUrl = API_BASE;})
//Controller calling
.controller('MainController',function($scope,urls, API_BASE) {
$scope.api_base = urls.apiUrl; // or API_BASE
});
//html 페이지에서 {{api_base}라고 부릅니다.
또한 다음과 같은 몇 가지 다른 옵션이 있습니다..value그리고..config하지만 그들 모두 한계가 있습니다. .config는, 초기설정을 실시하기 위해서 서비스 프로바이더에 연락할 필요가 있는 경우에 최적입니다. .value다른 유형의 값을 사용할 수 있다는 점을 제외하면 상수와 같습니다.
https://stackoverflow.com/a/13015756/580487
상수를 사용하여 해결합니다.프로바이더와 마찬가지로 .config 단계에서 설정할 수 있습니다.키스 모리스 같은 다른 것들은 다 전에 썼어실제 코드는 다음과 같습니다.
(function () {
var appConfig = {
};
angular.module('myApp').constant('appConfig', appConfig);
})();
그 후 app.bootstrap.displays로 이동합니다.
(function () {
angular.element(document).ready(function () {
function handleBootstrapError(errMsg, e) {
console.error("bootstrapping error: " + errMsg, e);
}
$.getJSON('./config.json', function (dataApp) {
angular.module('myApp').config(function (appConfig) {
$.extend(true, appConfig, dataApp);
console.log(appConfig);
});
angular.bootstrap(document, ['myApp']);
}).fail(function (e) {
handleBootstrapError("fail to load config.json", e);
});
});
})();
json 설정 파일에 대해서는 Jaco Pretorius 블로그에 프랙티스 예가 있습니다.기본적으로:
angular.module('plunker', []);
angular.module('plunker').provider('configuration', function() {
let configurationData;
this.initialize = (data) => {
configurationData = data;
};
this.$get = () => {
return configurationData;
};
});
angular.module('plunker').controller('MainCtrl', ($scope, configuration) => {
$scope.externalServiceEnabled = configuration.external_service_enabled;
$scope.externalServiceApiKey = configuration.external_service_api_key;
});
angular.element(document).ready(() => {
$.get('server_configuration.json', (response) => {
angular.module('plunker').config((configurationProvider) => {
configurationProvider.initialize(response);
});
angular.bootstrap(document, ['plunker']);
});
});
Pluker: http://plnkr.co/edit/9QB6BqPkxprznIS1OMdd?p=preview
참조: https://jacopretorius.net/2016/09/loading-configuration-data-on-startup-with-angular.html, 최종접속일 : 2018년 3월 13일
언급URL : https://stackoverflow.com/questions/22825706/angularjs-load-config-on-app-start
'codememo' 카테고리의 다른 글
| JSON 개체를 Custom C# 개체로 변환하는 방법 (0) | 2023.03.09 |
|---|---|
| JSON에서 빈 대 늘의 표기법은 무엇입니까? (0) | 2023.03.09 |
| 스프링 부트 구성에서 올바른 MySQL JDBC 시간대를 설정하는 방법 (0) | 2023.03.04 |
| 리액트 리듀스: 리듀서 조합:예기치 않은 키 (0) | 2023.03.04 |
| jQuery: serialize() 형식 및 기타 파라미터 (0) | 2023.03.04 |