Reputation: 57
I want a message to be displayed on file upload success or failure on the UI. I have the following file structure.
Controller:
My file upload function is like this:
$scope.uploadFile = function () {
//using a service
fileUpload.uploadFileToUrl(file, uploadUrl)
};
This works perfectly fine. The fileUpload service looks like this:
angular.module('myApp').service('fileUpload', ['$http', function
($http) {
//upload function happens here and returns a promise, This is executing fine.
.success(function (response) {
if (response.status=="uploadSuccess")
{
alert("The file has been successfully uploaded");
var message = "success";
}
if (response.status == "uploadFailure") {
alert("The file could not be uploaded");
}
if (response.status == "uploadFailureExc") {
alert("The file could not be uploaded due to an exception that occured");
}
if (response.status == "FileExists") {
alert("The file could not be uploaded - a file with that name already exists");
}
})
.error(function () {
});
}
}]);
How can I display a message on my html page instead of using alerts. I have tried to set a variable var message. and then returning it out of the service, but its going in some infinity loop and getting stuck. I have tried to use a scope variable and its also going in some infinite loop.
Help
Upvotes: 0
Views: 59
Reputation: 6900
$http
will trigger callback asynchronously when the response is available.
you can use .then
to get response from your Service
.then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
and in your controller
fileUpload.uploadFileToUrl(file, uploadUrl).then(function(data) {
console.log(data);
});
Upvotes: 1
Reputation: 1296
.success(function (response) {
if (response.status=="uploadSuccess")
{
var message = "The file has been successfully uploaded";
return message;
}
if (response.status == "uploadFailure") {
var message = "The file could not be uploaded";
return message;
}
if (response.status == "uploadFailureExc") {
var message = "The file could not be uploaded due to an exception that occured";
return message;
}
if (response.status == "FileExists") {
var message = "The file could not be uploaded - a file with that name already exists";
return message;
}
})
Replace the on success block with this code which returns a message for every condition upon upload and now you can use it in your controller in whichever way you want to. Hope this helps.!
Upvotes: 0