2017-10-27 7 views
0

は、私は私のコントローラ内のサービスからのエラーメッセージにアクセスしようとしていますコントローラ内部の角度サービスからのエラーを処理する方法は?私は角に新しいです

は、ここに私のサービスは

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

$http.postは約束を返します。その約束をuploadFileToUrl関数から返すことができます。そして誰かが結果と対話する必要があるならば、彼らはpromiseオブジェクトを使うことができます。

サービス:D:

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 :('); 
       } 
      ) 
    }; 
}); 
+0

おかげで、それは本当に便利だった、ただそれは時に立ち往生聞いてもいいです実現しました – Wayne

関連する問題