2016-07-22 115 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; 
      }) 

    };