hussain hussain - 1 month ago 4
Javascript Question

How to get data from angular service to controller?

I have response from server in success , How can i send that to controller i tried then method but its throwing error then is nto defined, How can i achieve this task ?

service.js

angular.module('App').service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
console.log('service called', fd);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(resp){
console.log('success',resp);
return resp;
})
.error(function(){
});
}
}]);


controller.js

$scope.uploadFile = function(){
var file = $scope.myFile;
// console.log('file is ');
// console.dir(file);
// console.log(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl).then(function(resp){console.log(resp);
};
};

Answer

Avoid using the .success (which is deprecated anyway) in the service, and just return the promise itself.

angular.module('App')

.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        // ... other code ...
        // return the $http promise itself here
        return $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
    }
}])

Then in your controller (the .catch is optional, but good to use if your $promise errors out).

$scope.uploadFile = function(){
    // ... other code ...
    var uploadUrl = "/fileUpload";

    fileUpload.uploadFileToUrl(file, uploadUrl)
        .then(function(response) { console.log(response) })
        .catch(function(error) { console.log(error) });
};
Comments