【问题标题】:Angular doesn't update my object after http requesthttp请求后Angular不会更新我的对象
【发布时间】:2015-02-13 02:07:23
【问题描述】:

这是我的角度代码:

samirsoftApp.controller("OrderCtrl",function($scope,$http){
$scope.currentStep=1;
$scope.defaultQuantity=1;
$scope.item={};
$scope.getItem = function(){
$http.get('/test/getItemDetails/')
.success(function(data, status, headers, config) {
$scope.$apply(function(){
$scope.item = data;
});
console.log($scope.item);
})
.error(function(data, status, headers, config) {
console.log(data)
});
};
});

当它请求并获得答案时,它不会更新我的项目对象,所以我使用了 $apply 并且它不起作用并引发错误: 错误:[$rootScope:inprog] http://errors.angularjs.org/1.3.13/$rootScope/inprog?p0=%24digest S/https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:6:417 .....

我也试过了

$timeout(function() {
$scope.item = data;
}, 0);

而不是 $apply` 但它在 consol 中打印一个空对象

是这样的:

samirsoftApp.controller("OrderCtrl",function($scope,$http,$timeout){
$scope.currentStep=1;
$scope.defaultQuantity=1;
$scope.item={};
$scope.getItem = function(){
$http.get('/test/getItemDetails/')
.success(function(data, status, headers, config) {
$timeout(function() {
$scope.item = data;
}, 0);
console.log($scope.item);
})
.error(function(data, status, headers, config) {
console.log(data)
});
};
});

我应该怎么做才能在 http 请求后更新我的对象。 谢谢

【问题讨论】:

  • 您尝试的第二件事是否因超时而不起作用?
  • 您确定您的 Ajax 请求确实返回了数据吗?如果您在请求中有 console.log() ,那会显示什么吗?
  • 不,它在控制台中显示一个空对象。这是为什么呢?
  • 是的,我很确定 ajax 请求,它返回一个 json,并且经过全面测试
  • 看起来你的端点实际上并没有返回值,看看你的服务器代码

标签: javascript angularjs


【解决方案1】:

你可以像这样分配$http.get()请求返回的数据

  $http.get('/test/getItemDetails/')
    .success(function(data, status, headers, config) {
      $scope.item = data;
      console.log($scope.item);
    })
    .error(function(data, status, headers, config) {
      console.log(data);
    });
  };

不需要$apply,因为角度会自动更新$scope

我怀疑问题出在您的代码的其他地方

可能:

  • 您定义了包含$http 请求的function#getItem,但您在哪里调用它?
  • 确保对 URL /test/getItemDetails/ 的调用是
    1. 通过手动浏览或使用 POSTMAN 等实用程序返回数据。
    2. 使用正确的 URL 调用 - 尝试在 developer tools > network 中检查 404 错误

我已经更新了你的代码 - 演示 这里 - http://jsbin.com/notudebiso/1/edit?html,js,output

(使用 $http 调用 github api)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    相关资源
    最近更新 更多