kkpatel kkpatel - 4 months ago 22
AngularJS Question

How can Angular Service Function return response to controller

Actually, I am uploading image using service, image uploaded successfully, but I want responded data to the function in controller.

Controller:

adminApp.controller('imageController', ['$scope', 'fileUpload', 'Images',function ($scope, fileUpload, Images) {

$scope.uploadFile = function (data) {
console.log(data);

var file = data.myFile;
console.log('file is ');
console.dir(file);
var uploadUrl = "/image";
fileUpload.uploadFileToUrl(file, data, uploadUrl);
// $scope.images.push();

};
}]);


Service:

adminApp.service('fileUpload', ['$http', function ($http) {

this.uploadFileToUrl = function (file, data, uploadUrl) {
var fd = new FormData();
fd.append('file', file);
fd.append('owner_id', data.owner_id);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function (data) {
// return data;
})
.error(function () {
});
}
}]);


laravel (backhand):

public function store(Request $request)
{
$image = $request->file('file');
$image = $this->imageRepository->makeImage($image);
return $image;
}


I function in service return responded data from backhand to controller, so I can push the value to
$scope.images
in controllers function.

Answer

You can take advantage of angular $q here.

Updated Service Function

this.uploadFileToUrl = function (file, data, uploadUrl) {
    var defer = $q.defer();

    var fd = new FormData();
    fd.append('file', file);
    fd.append('owner_id', data.owner_id);
    $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function (data) {
            // return data;
           defer.resolve(data);
        })
        .error(function (error) {
            defer.reject(error);
        });
  }

return defer.promise;

}]);

In your controller, you can use the function as

fileUpload.uploadFileToUrl(file, data, uploadUrl).then(function(response){

    //response contains your data form service

}).catch(function(error){

    // error variable contains error data from service.

});

the code is not tested.. but it should work or very close.

Comments