【问题标题】:how to handle errors from angular service inside controllers?如何处理控制器内部角度服务的错误?
【发布时间】:2018-04-08 21:13:51
【问题描述】:

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

这是我的服务的样子

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

});

【问题讨论】:

    标签: javascript angularjs file-upload


    【解决方案1】:

    $http.post 返回一个承诺,您可以从 uploadFileToUrl 函数返回该承诺。然后,如果有人需要与结果交互,他们可以使用 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 :(');
                  }
               )
        };
    });
    

    【讨论】:

    • 谢谢,这真的很有帮助,只是意识到卡住时可以询问:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多