unusuario
unusuario

Reputation: 161

How can I make my .factory return the result on a promise (.then)

I have this factory:

I'm basically trying to get a file to my server. And when I finish uploading it, I want it to return an answer.

    .factory('fileUpload', function($http) 
    {

        var ofileUpload = {};

        ofileUpload.uploadFileToUrl = function(file, uploadUrl)
        {
            var fd = new FormData();
            fd.append('file', file);
            return $http.post(uploadUrl, fd, {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
            })
            ,function(){
                ofileUpload.answer="success";
                ofileUpload.respuesta;

            },function(){
               ofileUpload.answer="failure";
               ofileUpload.answer;
            };
        }

        return ofileUpload;
    })

In my controller I am trying to do this:

  //I am executting this:
  fileUpload.uploadFileToUrl(file, uploadUrl).then(function(){
    console.log(fileUpload.answer)
  });

but this error appears to me.

TypeError: fileUpload.uploadFileToUrl(...).then is not a function

How can I have my .factory return the response on a promise to receive the value returned (ofileUpload.answer) in my controller?

Upvotes: 0

Views: 66

Answers (1)

unusuario
unusuario

Reputation: 161

I solved that. thank you!

    .factory('fileUpload', function($http) 
    {

        var ofileUpload = {};

        ofileUpload.uploadFileToUrl = function(file, uploadUrl)
        {
            var fd = new FormData();
            fd.append('file', file);
            return $http.post(uploadUrl, fd, {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
            }).then(function(data) {
                    ofileUpload.answer="success";
                },function(response) {
                    ofileUpload.answer="failure";
                });
        }

        return ofileUpload;
    })

Upvotes: 1

Related Questions