[英]How to test a controller in angular, that gets data from an angular service?
[英]How to get data from angular service to controller?
我已成功收到服務器的響應,如何將其發送到我嘗試過的方法中但未定義其拋出錯誤的控制器,我如何完成此任務?
service.js
angular.module('App').service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
console.log('service called', fd);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(resp){
console.log('success',resp);
return resp;
})
.error(function(){
});
}
}]);
controller.js
$scope.uploadFile = function(){
var file = $scope.myFile;
// console.log('file is ');
// console.dir(file);
// console.log(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl).then(function(resp){console.log(resp);
};
};
避免在服務中使用.success
(無論如何不推薦使用),而只返回諾言。
angular.module('App')
.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
// ... other code ...
// return the $http promise itself here
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
}
}])
然后在您的控制器中(.catch是可選的,但如果$ promise錯誤出錯,則很好用)。
$scope.uploadFile = function(){
// ... other code ...
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl)
.then(function(response) { console.log(response) })
.catch(function(error) { console.log(error) });
};
你必須返回承諾,只有這樣,你就可以使用then
在控制器中。
angular.module('App').service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
console.log('service called', fd);
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
}
}]);
像這樣更改您的代碼。
angular.module('App').service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl) {
var fd = new FormData();
fd.append('file', file);
console.log('service called', fd);
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
});
}
}
$scope.uploadFile = function() {
var file = $scope.myFile;
// console.log('file is ');
// console.dir(file);
// console.log(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl)
.then(function(resp) {
console.log('Your response here', resp);
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.