使用Angular 1.5.7我正在使用uploadEventHandlers
来取得进展。它在工厂中工作,但值不会在控制器中更新。
厂:
.factory("PostFactory", function($http,baseUrl) {
var service = {};
service.progressBar = 0;
service.progressCounter = 0;
service.createPost = function(payload) {
return $http({
data: payload,
url: baseUrl + 'api/post',
method: 'POST',
uploadEventHandlers: {
progress: function (e) {
if (e.lengthComputable) {
service.progressBar = (e.loaded / e.total) * 100;
service.progressCounter = service.progressBar;
console.error("Inside factory: " + service.progressCounter);
}
}
}
}).then(function(response){
return response.data;
});
return service;
});
}
控制器:
.controller('SendPostCtrl', function($scope,$timeout,PostFactory) {
var post = {
// all my data (including a base64 encoded image) to send to the server
}
$scope.uploadProgress = PostFactory.progressCounter;
$scope.$watch($scope.uploadProgress, function() {
console.error("Inside controller: " + $scope.uploadProgress);
});
var promise = PostFactory.createPost(post);
promise.then(function(response) {
//do stuff after the server response with success data
});
});
如图所示,控制台将是:
> Inside controller: 0
> Inside factory: 13.1
> Inside factory: 26.3
> Inside factory: 39.4
> Inside factory: 52.6
> Inside factory: 65.8
> Inside factory: 78.9
> Inside factory: 92.1
> Inside factory: 100
如何获得控制器内进度的实时更新?
答案 0 :(得分:0)
问题是您希望范围值 uploadProgress 指的是服务中 progressCounter 的值。 情况并非如此,因为 progressCounter 的值是一个数字,基本类型,而不是一个引用该行的引用类型
$scope.uploadProgress = PostFactory.progressCounter;
仅将 uploadProgress 的值设置为零。然后,当您更改服务中的 progressCounter 时,此更改不会反映回 uploadProgress 。这将导致永远不会触发$ watch。
一种解决方案是观察服务变量而不是范围变量
$scope.$watch('PostFactory.progressCounter', function() {
$scope.uploadProgress = PostFactory.progressCounter;
console.error("Inside controller: " + $scope.uploadProgress);
});