2015-05-20 59 views
0
var bar = dataService.makeHttpRequest("GET", "/documents/checkfilename/", null, 
      function (data, status, headers, config) { 
       // I can see `true` if I alert(data); here 
       // I want to return the contents of data because 
       // it's a true/false and would perform tasks based 
       // on it being true or false. 

       return data; 
      }); 

alert(bar); // this should alert `true` or `false` but is `undefined` 

爲什麼警報(bar)總是返回undefined?我知道data在上面的函數有truefalse,我能夠提醒它;但是,我想回報它,只有在事情真的時才做。

dataService.makeHttpRequest服務功能如下所示:

dataService.makeHttpRequest = function(requestType, urlString, dataObject, successFunc, errorFunc) { 
    $http({ 
     method:requestType, 
     url:$rootScope.serverAddress+urlString, 
     data:dataObject 
     }) 
     .success(successFunc) 
     .error(errorFunc); 
}; 
+1

你逝去的HTTP請求後執行的回調,所以酒吧的功能只是返回'makeHttpRequest',它不返回任何東西,所以你得到'undefined'。 – GillesC

回答

1

爲什麼你的方法makeHttpRequest被返回undefined最簡單的解釋是,好了,它實際上並沒有返回值(哪來的return聲明? )

但是,即使你回電話的結果$http它不會是你想要的。回調的全部意義在於處理異步操作 - 如果你想基於HTTP響應接收到的數據,就必須在回調本身來完成執行邏輯。

由於$http()返回一個承諾,一個更清潔的方式做你想做的事是什麼:

dataService.makeHttpRequest = function(requestType, urlString, dataObject) { 
    return $http({ 
     method:requestType, 
     url:$rootScope.serverAddress+urlString, //recommend taking this as a parameter instead of abusing $rootScope 
     data:dataObject 
    }); 
}; 

dataService.makeHttpRequest("GET", "/documents/checkfilename/", null).success(function (data, status, headers, config) { 
    //do whatever you want with "data" here 
}); //can also chain ".error" here to specify an error callback 
+0

是的,這是正確的答案。雖然有些情況下需要$ q來處理多個異步請求,即使它們是$ http – Eagle1