如何处理控制器内角度服务的错误?

时间:2017-10-27 09:43:40

标签: javascript angularjs file-upload

我是角色的新手,我正在尝试从我的控制器内的服务访问错误消息

这是我的服务看起来像

 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)
           });
        }
     }]);```

我在控制器内的上传功能如下所示

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


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

});

1 个答案:

答案 0 :(得分:1)

$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}
       })
    }])

控制器

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 :(');
              }
           )
    };
});
相关问题