获取 AngularJS 错误:“[$rootScope:inprog] $digest already in progress"没有手动 $apply [英] Getting AngularJS Error: "[$rootScope:inprog] $digest already in progress" without a manual $apply
问题描述
关于此错误的其他帖子总是包括有人在不使用安全应用的情况下尝试 $apply,但在我的示例中并非如此.我的函数成功返回了我从 API 请求的数据,但我无法清除这个错误,这让我发疯.每次在 $http 函数中调用 .success 之前,我都会在控制台中收到错误:[$rootScope:inprog] $digest already in progress".下面是我的控制器和服务.谢谢!
Other posts on this error always include someone trying to $apply without using a safe apply, but that's not the case in my example. My function IS successfully returning the data I requested from the API, but I can't clean this bug and it's driving me nuts. Every time before the .success is called in my $http function I get "Error: [$rootScope:inprog] $digest already in progress" in the console. Below are my controller and service. Thanks!
这是我的服务,其中包括一个使用有效负载发布 $http 调用的函数:
Here's my service including a function to post an $http call with a payload:
Services.service( 'CoolService', ['$q', '$rootScope', '$http', 'Auth', function($q, $rootScope, $http, Auth){
var service = {
create: function(payload){
var deferred = $q.defer();
$http({
'url': '/api/endpoint/',
'dataType':'json',
'method': 'POST',
data: payload
}).success(function(data,status, headers, config){
deferred.resolve(data);
})
.error(function(data, status, headers, config){
deferred.reject("Error in request.");
});
return deferred.promise;
}
}
return service;
}]);
这是我调用服务的控制器:
And here's my controller which calls the service:
controllers.controller('CoolCtrl',['$scope', '$modal', '$log','CoolService', function($scope, $modal, $log, CoolService){
getCoolData = function (input_data) {
CoolService.create(input_data).then(function(results){
new_cool = results.results;
}, function(error){
console.log("there was an error getting new cool data");
});
};
var payload = {
user_id: data1,
cool_id: data2,
}
var new_cool_data = getCoolData(payload);
console.log(new_cool_data);
}]);
var new_cool_data 下面的日志在异步操作之前被调用,但 new_cool 确实在 getCoolData 的 .then 语句中被分配.任何帮助摆脱此错误或使其总体上不糟糕的帮助将不胜感激!
The log below var new_cool_data gets called before the async operation, but new_cool does get assigned inside the .then statement within getCoolData. Any help getting rid of this bug or making it not crappy in general would be greatly appreciated!
这是整个错误:https://gist.github.com/thedore17/bcac9aec781ef9ba535b
推荐答案
添加这个小方法并调用它代替 apply()
Add this little method and call it inplace of apply()
function CheckScopeBeforeApply() {
if(!$scope.$$phase) {
$scope.$apply();
}
};
这篇关于获取 AngularJS 错误:“[$rootScope:inprog] $digest already in progress"没有手动 $apply的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!