簡體   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