繁体   English   中英

Angular.js提供者:返回之前解析$ 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
          });
        }
      }
    });
  }]
});

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

无论如何,服务的appAction方法将返回一个promise; 因此,我们保留appUrl的值:如果它为非null,则使用它来检索我们的数据。 否则,我们会连锁承诺:首先获取配置,然后获取真实数据。 类似于以下内容:

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();
          });
        }
      }
    };
  }]
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM