将值返回到Angular JS中的控制器

问题描述 投票:0回答:1

如果文件扩展区的大小是我的代码,我想从服务将数据发送回我的控制器。

myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function (fileData, uploadUrl) {
   if (fileData.size > 50000000) {
        var fd = new FormData();
        fd.append('file', fileData);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: { 'Content-Type': undefined }
        })
        .success(function () {

        })
        .error(function () {

        });
    }
    else {
       return "Image size is more than 5MB";
    }
   }
  }]);
javascript angularjs angular-services angular-controller
1个回答
0
投票

您应该使用$ q服务来推迟执行请求,例如-

myApp.service('fileUpload', ['$http','$q', function ($http,$q) {
this.uploadFileToUrl = function (fileData, uploadUrl) {
   if (fileData.size > 50000000) {
        var fd = new FormData();
        fd.append('file', fileData);
       var deferred = $q.defer();
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: { 'Content-Type': undefined }
        })
        .then(function (result) {
          deffered.resolve(result);
        },function(error) {
           deffered.reject();
        });
      return deferred.promise;
    }
    else {
       return "Image size is more than 5MB";
    }
   }
  }]);

有关更多信息,请检查以下链接-

https://docs.angularjs.org/api/ng/service/ $ q https://thinkster.io/a-better-way-to-learn-angularjs/promises

© www.soinside.com 2019 - 2024. All rights reserved.