2014-10-02 133 views
0

我正在使用angularjs調用服務器方法並獲取返回響應。但問題是來自angularjs服務的響應對控制器是空的。考慮我的代碼:Angularjs服務響應

testModule.factory('testService', ['$http', function ($http){ 

    return { 
     getResponse: getResponse 
    }; 

    function getResponse(url, data) 
    { 

     var returnResponse = {}; 

     $http({ 

      'url' : url, 
      'method' : 'POST', 
      'data' : data 
     }) 
     .success(function(response){ 

      returnResponse = response; 
      console.log(returnResponse); <-- here it prints the object with data inside. 
     }); 

     console.log(returnResponse); <-- here it prints empty value for returnResponse. 

     return returnResponse; 
    } 
}]); 

如代碼中所描述的問題是,成功之外的函數對象獲得null或空值。請提出建議。 謝謝。

+0

檢查HTTP請求的響應標頭。 99%的機會出現跨域安全性失敗,例如99%的新角色開發人員進行WS調用。 – 2014-10-02 11:38:34

回答

1

這是因爲http請求您正在調用的請求是異步調用。

你可能會想像一個不同的線程正在執行那個函數,而其餘的函數會繼續正常執行。

所以, 只要你打$ HTTP(..)

| . 
v . 
| $http(....) -----> I would go and get it evaluated asynchronously 
V      When I finish, I will execute anything that lies in success 
|       callback 
v console.log(...); ------> I will not wait for success to call, that is an async 
|        operation I will print the value of returnResponse just 
v        after I hit $http(...), I won't wait for its response 

因此,你的console.log(),這是成功的回調,returnResponse外,沒有任何關係,因此打印未定義或null。

你可以在這裏使用的重要概念是Promises或Q.瀏覽它。這應該是一個安全的手段來解決你的問題。

希望你明白。

+0

感謝您的回覆和建議。 – user3406754 2014-10-08 13:12:26