我正在为一个名为'UploadService'的上传的可重用代码构建一个Angular服务,该代码在下面的控制器中被调用 - 即使服务已被加载,我也总是得到以下错误
`UploadService.upload is not a function at h.$scope.uploadImage...)`
我的上传服务(UploadService.js)
abcdServices.service('UploadService', function(ApiService, $http, $localStorage, $location, $timeout, $q, $rootScope, Upload) {
var UploadService = function() {
this.upload_in_progress = false;
this.attached_media = {
photos: [],
videos: []
}
};
UploadService.prototype.upload = function(files) {
console.log('get here');
};
return UploadService;
});
//调用服务的我的控制器 - 注意我已将其添加到
$scope.uploadImage = function(files, fileIndex, imageIndex) {
console.log('existing upload image');
console.log(files); // this shows an array in the console log as expected
UploadService.prototype.upload(files);
}
//控制器在顶部加载了服务,我在index.php中包含了UserService.js文件
abcdControllers.controller('PostController', function( $http, $rootScope, UploadService) {
答案 0 :(得分:1)
原型只是一种将实例成员添加到“类”的javascript方式。关键是,您必须直接使用UploadService.upload()
而不是原型 UploadService.prototype.upload()
,因为UploadService
不是对类的引用,angularjs'注入器为您提供该类的一个实例,当您声明服务UploadService
时,angularjs会将单个引用注入new UploadService()
。
此外,您以错误的方式声明服务类,您的方法不返回注入器的UploadService类,它只返回一个返回UploadService的函数,该函数从未公开过。更好的方法就是下面的代码:
abcdServices.service('UploadService', function UploadService(ApiService, $http, $localStorage, $location, $timeout, $q, $rootScope, Upload) {
this.upload_in_progress = false;
this.attached_media = {
photos: [],
videos: []
};
this.upload = function(files) {
console.log('get here');
};
});
或者您只需将其更改为工厂提供商并返回“Class”的新实例:
abcdServices.factory('UploadService', function(ApiService, $http, $localStorage, $location, $timeout, $q, $rootScope, Upload) {
var UploadService = function() {
this.upload_in_progress = false;
this.attached_media = {
photos: [],
videos: []
};
};
UploadService.prototype.upload = function(files) {
console.log('get here');
};
return new UploadService();
});