在Angular JS中获取HTTP请求的值

问题描述 投票:2回答:2

我尝试创建一个函数,在Javascript中生成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] */
    };

请问你能帮帮我吗?

javascript angularjs asynchronous httprequest deferred
2个回答
1
投票

使用Promise时应该像这样继续:

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

您当前的代码返回Promise,这就是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服务的一个常见错误是将此服务方法的返回值分配给变量,该变量是一个不是您想要的承诺。

考虑下面的代码:

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

    };
© www.soinside.com 2019 - 2024. All rights reserved.