0

之前解決$ http請求我有一個供應商,看起來像下面這樣:Angularjs提供商:返回

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

目前的應用程序設置appUrl作爲構建的一部分生成基於常數的.config塊使用grunt ngconstant進行處理。

我試圖將應用程序更改爲通過$ 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 
      }); 
     } 
     } 
    }); 
    }] 
}); 

這會將從遠程資源的配置,但返回一個承諾,而不是實際的功能的不良副作用。我已經嘗試(不成功)解決承諾,然後從提供程序返回值。我不想改變我的應用程序的其餘部分,以期望得到一個承諾,而不是返回一個函數。確保此方法返回一個函數的最佳方法是什麼?

+0

您會如何期待它的正常工作?您正在執行異步操作,並且操作方式是使用承諾。你不能(也不應該)阻止承諾,你也不能像同步呼叫那樣對待它。 –

+0

保留原始代碼。當應用程序加載時,加載config.json文件,然後將setAppUrl與response.appUrl – Hoyen

+0

@Hoyen除非我錯過了某些東西,您不能在.config塊中使用$ http – biagidp

回答

1

該服務的appAction方法無論如何都返回一個承諾;所以我們保留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(); 
      }); 
     } 
     } 
    }; 
    }] 
});