先在Angular中加载配置文件,然后再加载其他文件

Loading config file in Angular, before everything else

本文关键字:加载 其他 文件 然后 配置文件 Angular 先在      更新时间:2023-09-26

我想在Angular应用程序中加载配置文件,只有在第一次打开应用程序时。然后,配置变量在整个应用程序中变得全局可用。以下是我目前在app.js:中发现的内容

angular
  .module('myApp', [
    ...
  ])
  .run(
    [ '$rootScope', '$http',
      function ($rootScope,  $http) {
        $http.get('config/config.json').success(function(data) {
            $rootScope.config = data;
        });

      }
    ]
  )

在这里,我加载config.js,当我试图在我的控制器中使用它时,如下所示:

  angular.module('myApp')
    .controller('MainCtrl', function ($rootScope) {
      console.log($rootScope, $rootScope.config);
    })

对于$rootScope,我可以看到包括config在内的所有属性,但$rootScope.config返回未定义

如何在第一页加载config文件,然后使其在整个应用程序中可访问?

谢谢!

正如Mark Colemans的博客文章中所描述的那样,您可以获取配置,然后加载应用程序。粘贴标记代码以方便:

var urlToCheck = '/echo/json/';
var myApp = angular.module('myApp', []);
myApp.controller("MyCtrl", ["$scope", "config", function ($scope, config) {
    $scope.url = config.url;
}]);
$.ajax({
    url: urlToCheck
}).fail(function () {
    myApp.constant('config', {
        url: '/fail-url'
    });
}).done(function () {
    myApp.constant('config', {
        url: '/done-url'
    });
}).always(function () {
    angular.bootstrap(document, ['myApp']);
});

您可以将其初始化为promise,然后在解析promise时在控制器中访问它。也拒绝承诺。

http://plnkr.co/edit/EIBJhZg80lpeyhkMD3FD

$q.when($rootScope.config).then(function (config) {
  console.log($rootScope.config, config);  
});