Angularjs 在数据库中持久化超出get请求的范围

Angularjs 在数据库中持久化超出get请求的范围,angularjs,angularjs-scope,angularjs-http,Angularjs,Angularjs Scope,Angularjs Http,我有以下代码: $http({ method: 'GET', url: 'http://localhost:8080/getStuff' }).then(function successCallback(response) { $scope.stuffData= response.data.length; }, function errorCallback(response) { }); console.log("amount is:" +$

我有以下代码:

  $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
其他一些问题建议运行$scope。$apply使我的作用域保持不变。为此,我得到以下错误:

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

保持我的范围的正确方法是什么?例如,将get请求的值分配给作用域变量的正确方法是什么?

HTTP调用是异步的。在应用程序检索数据之前,您的
控制台.log
可能会被调用。调用
console.log
时,
$scope.stuffData
尚未定义

控制台。日志
移动到
。然后

$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) {
});
$http({
方法:“GET”,
网址:'http://localhost:8080/getStuff'
}).then(函数成功回调(响应){
$scope.stuffData=response.data.length;

console.log(“amount is:,$scope.stuffData);//HTTP请求异步运行。为了处理这个概念,您必须使用

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

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

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

在检索数据之前执行console.log()(http调用是异步的),因此值尚未定义。成功后,请尝试检查函数内的值:

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

这并不能解决问题。我希望结果在请求之外持久化。确实如此。因为您将其存储在
$scope
中,请尝试在HTML中显示它。例如:
{{stuffData}
@MattBoyle您能再次检查您的问题是否得到解决吗?可能的重复并不能解决问题。我希望结果在请求之外保持不变。我想,一旦承诺返回,我希望将该值分配给作用域?当然。您需要从作用域上的响应中删除数据。但即使这样也不够。您的
console.log
在回调函数运行之前运行。这就是您的
$scope.stuffData
未定义的原因。
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) {
    });




});