【问题标题】:Persisting Scope beyond get request in Angular在 Angular 中保持超出获取请求的范围
【发布时间】:2017-01-16 23:41:21
【问题描述】:

我有以下代码:

  $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

其他一些 SO 问题建议运行 $scope.$apply 以使我的范围持续存在。为此,我收到以下错误:

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

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

【问题讨论】:

标签: angularjs angularjs-scope angularjs-http


【解决方案1】:

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

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

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

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

【讨论】:

  • 这并不能解决问题。我希望结果在请求之外持续存在。我想一旦返回承诺,我希望将该值分配给范围?
  • 非常。您需要从范围内的响应中分配数据。但即使这样也不够。您的console.log 在回调函数运行之前运行。这就是您的$scope.stuffData 未定义的原因。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 这并不能解决问题。我希望结果在请求之外持续存在。
    • 确实如此。由于您将其存储在 $scope 中,因此请尝试以 HTML 格式显示它。例如:&lt;div&gt;{{stuffData}}&lt;/div&gt;.
    • @MattBoyle 您能否再次检查您的问题是否已解决?
    【解决方案4】:
    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) {
        });
    
    
    
    
    });
    

    【讨论】:

      猜你喜欢
      • 2017-03-09
      • 2013-12-14
      • 2011-04-19
      • 1970-01-01
      • 1970-01-01
      • 2021-06-08
      • 2016-08-18
      • 2012-12-15
      • 2014-09-30
      相关资源
      最近更新 更多