Angularjs 提供商:返回前解析 $http 请求

Angularjs provider: Resolve $http request before returning

我有一个如下所示的提供程序:

angular.module('myProvider', function(){
  var appUrl = ''
  this.setAppUrl = function(url){
    appUrl = url;
  }
  this.$get = ['$http', function($http){
    return {
      appAction: function(){
        $http.get(appUrl).then(function(response){
          //do stuff
        });
      }
    }
  }]
});

目前,该应用程序根据在构建过程中使用 grunt ngconstant 生成的常量在 .config 块中设置 appUrl。

我正在尝试将应用更改为通过 $http 从 json 文件加载配置文件。提供商现在看起来像这样:

angular.module('myProvider', function(){
  this.$get = ['$http', function($http){
    return $http.get('path/to/config.json').then(function(response){
      appUrl = response.appUrl;
      return {
        appAction: function(){
          $http.get(appUrl).then(function(response){
            //do stuff
          });
        }
      }
    });
  }]
});

这会从远程源加载配置,但会产生不需要的副作用,即返回承诺而不是实际函数。在从提供者返回值之前,我已经尝试(未成功)解决承诺。我不想更改我的应用程序的其余部分以期望返回一个承诺而不是一个函数。确保此方法 returns 是一个函数的最佳方法是什么?

服务的appAction方法returns无论如何都是一个承诺;所以我们保留 appUrl 的值:如果它是非空的,我们用它来检索我们的数据。否则我们链式承诺:首先检索配置,然后检索真实数据。类似于以下内容:

angular.module('myProvider', function(){
  this.$get = ['$http', function($http){
    var appUrl;

    function retrieveTheRealData() {
      return $http.get(appUrl).then(function(response){
        //do stuff
      });
    }

    return {
      appAction: function() {
        if( appUrl ) {
          return retrieveTheRealData();
        }
        else {
          return $http.get('path/to/config.json').then(function(response){
            appUrl = response.appUrl;
            return retrieveTheRealData();
          });
        }
      }
    };
  }]
});