Angular App启动前如何从.json文件加载某些设置 [英] How is possible to load some setting from .json file before angular app starts

查看:305
本文介绍了Angular App启动前如何从.json文件加载某些设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建使用CORS请求的应用程序.我使用的每个请求都从常量获取主机地址

i'm building application which uses CORS requests. Each request i use get host address from a constant

angular.module('siteApp').constant('baseUrl', {
'server':'htttp://localhost/',
})

在每项服务中,我都使用这种方式发送请求:

And in each service i use to send request like this:

angular.module('siteApp').factory('DocsSvc', function ($http, baseUrl) {
   var baseurl = baseUrl.server ;
   $http.get(baseurl + 'document')

是否可以使'htttp://localhost/'值-从config.json文件进入baseUrl常量或baseUrl工厂? 我的意思是:我该如何从ajax加载某些内容,以使其可以被应用模块访问

Is it possible to make 'htttp://localhost/' value - to came from config.json file into baseUrl constant or baseUrl factory? I mean : how can i load something from ajax request an make it accessible to app modules

我尝试过:

.run(['$rootScope', , function ($rootScope) {

  $.ajax('config.json', {async: false})
  .success(function (data) {
    $rootScope.HOST = data.HOST;
  });

并尝试从baseUrl访问它:

And tried to access it from baseUrl:

angular.module('siteApp').factory('baseUrl',function($rootScope) {
 return {
  server: $rootScope.HOST

但是没有运气-baseUrl.server未在函数中定义

But no luck - the baseUrl.server comes undefined into functions

推荐答案

您可以使用run角度方法.

  var app = angular.module('plunker', []);

  app.run(function($http, $rootScope){
  $http.get('config.json')
  .success(function(data, status, headers, config) {
    $rootScope.config = data;
    $rootScope.$broadcast('config-loaded');
  })
  .error(function(data, status, headers, config) {
    // log error
    alert('error');
  });
})

app.controller('MainCtrl', function($scope, $rootScope) {
  $scope.$on('config-loaded', function(){
    $scope.name = $rootScope.config.name;  
  });
});

查看此朋克车

这篇关于Angular App启动前如何从.json文件加载某些设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆