我有Angular服务,可以在移动应用程序中上传Cordova文件传输 - 它将文件上传到媒体服务器并返回一个对象。我试图将此对象传递给media_response
属性,但我没有运气 - 我做错了什么?
请注意 - 我已尝试使用service
和factory
,但似乎仍然没有任何乐趣 - $cordovaFileTransfer upload
块中的任何内容都未传递给类属性,因为有些奇怪原因。
我希望看到media_response
与数据变量具有相同的输出,数据变量是从媒体服务器返回的对象,但它显示no response
知道为什么我没有得到预期的回应吗?
//预期回复
UploadService.media_response in the controller should be an object to match the console.log(data)
//实际回复
UploadService.media_response is the string 'no response'
//上传服务
abcdServices.service('UploadService', function($http, $localStorage, $location, $q, $rootScope, $cordovaFileTransfer) {
var UploadService = function() {
this.upload_in_progress = false;
this.progress = 0;
this.media_response = '';
};
UploadService.prototype.cordovaFileUpload = function (filename, url, targetPath) {
this.upload_in_progress = true;
this.media_response = 'no response';
var options = {
id: new Date() . getTime() + filename,
fileKey: "file",
fileName: filename,
chunkedMode: false,
mimeType: "multipart/form-data",
params : {'fileName': filename}
};
$cordovaFileTransfer.upload(url, targetPath, options).then(
function(result) {
// Success!
var data = JSON.parse(result.response);
console.log('file uploaded - response:', data); // ALWAYS A OBJECT
this.media_response = 'fake response2';
UploadService.media_response = 'fake response3';
if (angular.isDefined(data.id)) {
angular.forEach(data, function(value, key) {
// image[key] = value;
});
// $scope.post.linkThumbnail = false;
// $scope.post.video = '';
} else if (angular.isDefined(data.message)) {
// $scope.uploadError = data.message;
} else {
}
}, function(err) {
}, function (progress) {
// constant progress updates
this.progress = parseInt(100 * progress.loaded / progress.total) + '%';
}
);
};
return new UploadService();});
//控制器
UploadService.cordovaFileUpload(filename, url, targetPath, options);
console.log(UploadService); // to view in js console
答案 0 :(得分:0)
您的this.
变量的范围限定为最近的功能块,而不是服务/工厂。
使用var
或let
在服务/工厂的根目录中创建变量。
abcdServices.service('UploadService', function($http, $localStorage, $location, $q, $rootScope, $cordovaFileTransfer) {
let upload_in_progress = false;
let progress = 0;
let media_response = '';
var UploadService = function() {
upload_in_progress = false;
progress = 0;
media_response = '';
};
UploadService.prototype.cordovaFileUpload = function (filename, url, targetPath) {
upload_in_progress = true;
media_response = 'no response';
// Rest of your code
};
return new UploadService();});
如果您确实需要/想要使用this
,请使用新功能箭头表示法,它不会在功能块中创建新的this
范围。
abcdServices.service('UploadService', function(...) {
this.upload_in_progress = 'test';
this.progress = 0;
this.media_response = '';
someFunction = (param1, param2, ..) => {
console.log(this.upload_in_progress) // 'test'
}
});