我有一个代码可以在控制器中上传文档,我希望将它移动到服务中,以便其他控制器可以使用它。
"use strict";
angular.module('myApp')
.service('uploadDocumentService', ['Upload', function (Upload) {
this.UploadDocument = function ($file, data) {
Upload.upload({
url: '/uploadDocuments',
file: $file,
data: data
}).progress(function (evt) {
var progressReport = {};
progressReport.progressVisible = true;
progressReport.percentage = Math.round(evt.loaded / evt.total * 100);
return progressReport;
}).success(function (data, status, headers, config) {
var fileUploaded = {};
fileUploaded.id = data.id;
fileUploaded.name = data.fileName;
return fileUploaded;
});
}
}]);
我无法捕获控制器中的.progress事件
uploadDocumentService.UploadDocument($file, 'Path')
.progress(function (progressReport) {
//Some code
}).success(function (data) {
//Some code
});
继续获取错误无法读取未定义的属性“进度” at m。$ scope.uploadDocuments 有关如何解决此问题的任何提示,我是否需要在服务中注册进度事件?
答案 0 :(得分:1)
控制器代码
"use strict";
angular.module('myApp')
.controller('controller', ['$scope', '$http', 'Upload', 'uploadDocumentService', function ($scope, $http, Upload, uploadDocumentService) {
$scope.uploadDocuments = function ($files) {
$scope.progressVisible = false;
for (var i = 0; i < $files.length; i++) {
var $file = $files[i];
uploadDocumentService.UploadDocument($file, 'path')
.progress(function (evt) {
$scope.progressVisible = true;
$scope.percentage = Math.round(evt.loaded / evt.total * 100);
}).success(function (data) {
var fileUploaded = {};
fileUploaded.id = data.id;
fileUploaded.name = data.fileName;
$scope.filesUploaded.push(fileUploaded);
$scope.isFileUploaded = true;
});
}]);
答案 1 :(得分:1)
一位同事指出了错误,修复如下,语句中没有返回上传.upload
"use strict";
angular.module('myApp')
.service('uploadDocumentService', ['Upload', function (Upload) {
this.UploadDocument = function ($file, data) {
return Upload.upload({
url: '/uploadDocuments',
file: $file,
data: data
}).progress(function (evt) {
}).success(function (data, status, headers, config) {
});
}
}]);
答案 2 :(得分:0)
要获得预期的结果,请在控制器函数中添加uploadDocumentService参数。
angular.module('myApp').controller("controller", function($scope, uploadDocumentService)