简体   繁体   English

Angular.js提供者:返回之前解析$ http请求

[英]Angularjs provider: Resolve $http request before returning

I have a provider that looks something like the following: 我有一个提供者,看起来像下面这样:

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

Currently the app sets the appUrl in a .config block based on constants generated as part of the build process using grunt ngconstant. 当前,应用程序根据使用grunt ngconstant作为构建过程的一部分生成的常量在.config块中设置appUrl。

I'm trying to change the app over to loading the config file from a json file via $http. 我正在尝试将应用程序更改为通过$ http从json文件加载配置文件。 The provider now looks something like this: 提供者现在看起来像这样:

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

This loads the config from the remote source, but has the unwanted side effect of returning a promise instead of an actual function. 这会从远程源加载配置,但是会产生不良的副作用,即返回promise而不是返回实际功能。 I've tried (unsuccessfully) to resolve the promise before returning the value from the provider. 在从提供程序返回值之前,我尝试过(未成功)解决诺言。 I don't want to change the rest of my application to expect a promise instead of a function to be returned. 我不想更改我的应用程序的其余部分以期望有一个承诺,而不是返回一个函数。 What's the best way to make sure that this method returns a function? 确保此方法返回函数的最佳方法是什么?

The appAction method of the service returns a promise anyway; 无论如何,服务的appAction方法将返回一个promise; so we keep the value of appUrl : if it is non-null, we use it to retrieve our data. 因此,我们保留appUrl的值:如果它为非null,则使用它来检索我们的数据。 Otherwise we chain promises: first retrieve the configuration, then retrieve the real data. 否则,我们会连锁承诺:首先获取配置,然后获取真实数据。 Something like the following: 类似于以下内容:

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