2017-01-16 52 views
0

我有以下代码:坚持适用范围超出GET请求角

$http({ 
    method: 'GET', 
    url: 'http://localhost:8080/getStuff' 
    }).then(function successCallback(response) { 
     $scope.stuffData= response.data.length; 
    }, function errorCallback(response) { 
    }); 

console.log("amount is:" +$scope.stuffData); 


}); 

在这种情况下,我的日志给:

amount is:undefined 

其他一些做题建议运行$范围$申请。使我的范围持久。为此,我收到以下错误:

angular.js:13920 Error: [$rootScope:inprog] $digest already in progress 

什么是保持范围的正确方法? I.E将一个get请求的值赋给一个scope变量的正确方法是什么?

+0

的[?我如何返回从一个异步调用的响应(可能的复制http://stackoverflow.com/questions/14220321/how -do-i-return-the-an-asynchronous-call) –

回答

0

HTTP调用是异步。您的console.log可能在之前被称为您的应用检索了数据。当调用console.log时,$scope.stuffData尚未定义。

将您的console.log移动到.then

$http({ 
    method: 'GET', 
    url: 'http://localhost:8080/getStuff' 
}).then(function successCallback(response) { 
     $scope.stuffData = response.data.length; 
     console.log("amount is:", $scope.stuffData); // <-- It should work 
}, function errorCallback(response) { 
}); 
+0

这并不能解决问题。我希望结果在请求之外持续存在。 –

+0

**它确实**。由于您将其存储在'$ scope'中,因此请尝试在HTML中显示它。例如:'

{{stuffData}}
'。 – Mistalis

+0

@MattBoyle你能否再次检查是否解决了你的问题? – Mistalis

0

HTTP请求以异步方式运行。为了处理这个概念,你必须使用promises

Angular使用回调函数来处理异步HTTP调用。

在你的情况下,$scope.stuffData是未定义的,因为console.log在http请求获得数据之前运行.then()回调函数。

如果您在.then()函数中添加了console.log,则可以解决此问题。

+0

这并不能解决问题。我希望结果在请求之外持续存在。我猜一旦这个承诺被退回,我想把这个值分配给范围? –

+0

Excatly。您需要将范围内的响应数据分配给您的范围。但即使这还不够。您的'console.log'在**回调函数运行之前运行**。这就是您的$ scope.stuffData未定义的原因。 – Korte

0

在检索数据(http调用是异步)之前执行console.log(),所以该值尚未定义。请检查里面的函数值,成功后:

$http({ 
    method: 'GET', 
    url: 'http://localhost:8080/getStuff' 
    }).then(function successCallback(response) { 
     $scope.stuffData= response.data.length; 
     console.log("amount is:" +$scope.stuffData); 
    }, function errorCallback(response) { 
     console.log("Response error"); 
    }); 
}); 
-1
try with this one please-- 

$http({ 
    method: 'GET', 
    url: 'http://localhost:8080/getStuff' 
    }).then(function successCallback(response) { 
     var obj = JSON.parse(response); 
     $scope.stuffData= obj.data.length; 
     $scope.$apply(); 
     console.log($scope.stuffData); 
    }, function errorCallback(response) { 
    }); 




});