gpt4 book ai didi

javascript - 如何处理 Controller 内部 Angular 服务的错误?

转载 作者:行者123 更新时间:2023-12-03 03:10:23 26 4
gpt4 key购买 nike

我是 Angular 新手,我正在尝试从 Controller 内的服务访问错误消息

这是我的服务

 admin.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);

$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})

.success(function(response){
console.log(response)
})

.error(function(response){
console.log(response)
});
}
}]);```

我的 Controller 内的上传功能如下所示

admin.controller('uploadCtrl', function($scope, fileUpload){


$scope.uploadFile = function(){
var file = $scope.myFile;
var uploadUrl = "/upload-url/";
fileUpload.uploadFileToUrl(file, uploadUrl)
};

});

最佳答案

$http.post 返回一个 promise ,您可以从 uploadFileToUrl 函数返回该 promise 。然后,如果有人需要与结果交互,他们可以使用 Promise 对象。

服务:

admin.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);

//VVVVVV---------- added return statement
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
}])

Controller

admin.controller('uploadCtrl', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
var uploadUrl = "/upload-url/";
fileUpload.uploadFileToUrl(file, uploadUrl)
//VVVVVV------------ added .then and callbacks
.then(
function (result) {
console.log('success!');
},
function (error) {
console.log('error :(');
}
)
};
});

关于javascript - 如何处理 Controller 内部 Angular 服务的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46972083/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com