简体   繁体   中英

Angular $http.post value from promises

I would like to ask you how to send data through $http.post which I get from the function using $q.defer().

Here is the bit of code:

HTML

<input type='text' ng-model='name'/>
<input type='file' id='inputFile' />
<button ng-click='save'>Save</button>

JavaScript

file = document.getElementById('inputFile');

function imgToBase64(file_input) {
    var deferred = $q.defer();
    if (file_input.files && file_input.files[0]) {
        var fileReader = new FileReader();
        fileReader.onload = function (event) {
            result = event.target.result;
            deferred.resolve(result);
        };
        fileReader.readAsDataURL(file_input.files[0]);
    }
    return deferred.promise;
};

imgToBase64(file).then(function(result){
   $rootScope.result = result;
});

Post request

$http.post(apiURL, {
  name: $scope.name,
  image: $rootScope.result
}).success(function(data) {
      console.log(data);
})

The problem is, that when i hit save, then content of 'name' is sent, but the $rootScope.result is empty. Even though when I put $rootScope.result to console.log() I can see the result, but in the post it is empty? What can be possibly doing wrong? Thanks

I don't know if this is what you want:

$scope.save = function () {
    imgToBase64(file).then(function (result) {
        $rootScope.result = result;
        $http.post([...]);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM