2016-07-22 107 views
2

我嘗試創建一個函數,該函數在Javascript中生成HTTP請求並獲取此請求的結果。不幸的是,我絕對不知道如何回到這個結果在其他功能..獲取Angular JS中HTTP請求的值

在這裏找到我的函數的兩個(兩者都應該做同樣的事情):

$scope.getInfo = function() { 
     return $http({ 
      method: 'GET', 
      url: 'https://api.net' 
     }).then(function (response) { 
      return response.data; 
     }); 
    }; 

而另外一個:

$scope.getInfo = function() { 
     var defer = $q.defer(); 
     $http.get('https://api.net').then(function(response) { 
      defer.resolve(response.data); 
     }, function(response) { 
      defer.reject(response); 
     }); 
     return defer.promise; 
    }; 

我已經找到了很多篇關於發出請求的方式,但不能取回它的值(函數在其他一個簡單的電話只顯示「目標對象」,我沒」找到正確顯示的解決方案)。

$scope.test = function() { 
     var myValue = $scope.getInfo(); 
     alert(myValue); /* show [Object object] */ 
    }; 

你能幫我嗎?

回答

1

使用承諾時,你應該這樣進行:

$http({ 
    method: 'GET', 
    url: 'https://api.net' 
}).then(function (response) { 
    $scope.info = response.data 
}); 

您當前的代碼返回一個承諾,這就是爲什麼通過的getInfo返回的結果被認爲是一個對象

如果你想的getInfo成爲功能,您可以這樣做:

$scope.getInfo = function() { 
    return $http({ 
     method: 'GET', 
     url: 'https://api.net' 
    }).then(function (response) { 
     return response.data; 
    }); 
}; 

$scope.getInfo().then(function(result) { 
    alert(result); 
}); 
1

使用$http服務的一個常見錯誤是指定這SERV的返回值冰方法的變量,這是一個不是你想要的承諾。

考慮下面的代碼:

$scope.getInfo = function() { 
     return $http({ 
      method: 'GET', 
      url: 'https://api.net' 
     }).then(function (response) { 
      return response.data; 
     }).catch(function(error){ 
      // do something with error 
      throw error; 
     }); 
    }; 

getInfo是返回一個承諾,在今後的這一承諾將解決到您想要的數據值的方法。

如果你在你的控制器使用這樣的:

$scope.test = function() { 
     var myValue = $scope.getInfo(); 
     alert(myValue); /* show [Object object] */ 
    }; 

myValue價值承諾(你可以簡單地做一個console.log(myValue)),建議的方法是使用這種方法象下面這樣:

$scope.test = function() { 
     $scope.getInfo() 
      .then(function(response){ 
       var myValue = response.data; 
       alert(myValue); /* show [Object object] */ 
      }).catch(function(error) { 
       console.log(error); 
       throw error; 
      }) 

    };