How to know from controller if http.post().then... was successful? - angularjs

I have a controller which uses the following line to post data to server through a factory called SendDataFactory:
SendDataFactory.sendToWebService(dataToSend)
And my factory SendDataFactory looks like this:
angular
.module('az-app')
.factory('SendDataFactory', function ($http, $q) {
var SendData = {};
/**
* Sends data to server and
*/
SendData.sendToWebService = function (dataToSend) {
var url = "example.com/url-to-post";
var deferred = $q.defer();
$http.post(url, dataToSend)
//SUCCESS: this callback will be called asynchronously when the response is available
.then(function (response) {
console.log("Successful: response from submitting data to server was: " + response);
deferred.resolve({
data: data
});
},
//ERROR: called asynchronously if an error occurs or server returns response with an error status.
function (response) {
console.log("Error: response from submitting data to server was: " + response);
deferred.resolve({
data: data
});
}
);
return deferred.promise;
}
return SendData;
});
I have seen some examples in here and the internet with
$http.post().success...
but I want to use
$http.post().then...
since angular documentation says:
The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
What I need:
Now in my controller I need to check if the $http.post().then... was successful or not and then do something based on success or fail. How can I achieve this?

I think this is what you meant:
$http.post(url, dataToSend)
//SUCCESS: this callback will be called asynchronously when the response is available
.then(function (response) {
console.log("Successful: response from submitting data to server was: " + response);
deferred.resolve({
data: response //RETURNING RESPONSE SINCE `DATA` IS NOT DEFINED
});
},
//ERROR: called asynchronously if an error occurs or server returns response with an error status.
function (response) {
console.log("Error: response from submitting data to server was: " + response);
//USING THE PROMISE REJECT FUNC TO CATCH ERRORS
deferred.reject({
data: response //RETURNING RESPONSE SINCE `DATA` IS NOT DEFINED
});
}
);
return deferred.promise;
}
In your controller you now can use:
SendDataFactory.sendToWebService(dataToSend)
.then(function(data) { /* do what you want */ })
.catch(function(err) { /* do what you want with the `err` */ });

Reject the promise instead of resolving it when it is rejected by $http.
/**
* Sends data to server and
*/
SendData.sendToWebService = function (dataToSend) {
var url = "example.com/url-to-post";
var deferred = $q.defer();
$http.post(url, dataToSend)
//SUCCESS: this callback will be called asynchronously when the response is available
.then(function (response) {
console.log("Successful: response from submitting data to server was: " + response);
deferred.resolve(response.data); // Resolving using response.data, as data was not defined.
},
//ERROR: called asynchronously if an error occurs or server returns response with an error status.
function (response) {
console.log("Error: response from submitting data to server was: " + response);
deferred.reject(response.data); // Rejecting using response.data, as data was not defined.
}
);
return deferred.promise;
}
You can then call it from your controller the same way as you handle the callback in the service using then.
Since $http returns a promise, it can be simplified further though using promise chaining. This way there is no need to use an extra deferred object.
/**
* Sends data to server and
*/
SendData.sendToWebService = function (dataToSend) {
var url = "example.com/url-to-post";
return $http.post(url, dataToSend)
//SUCCESS: this callback will be called asynchronously when the response is available
.then(function (response) {
console.log("Successful: response from submitting data to server was: " + response);
return response.data; // Resolving using response.data, as data was not defined.
},
//ERROR: called asynchronously if an error occurs or server returns response with an error status.
function (response) {
console.log("Error: response from submitting data to server was: " + response);
return $q.reject(response.data); // Rejecting using response.data, as data was not defined.
}
);
}

Related

AngularJS what is difference between $http success and then

various people use $http different way. say sample 1
$http({
method: 'GET',
url: 'api/book/',
cache: $templateCache
}).
success(function (data, status, headers, config) {
$scope.books = data;
}).
error(function (data, status) {
console.log("Request Failed");
});
here success and error callback is there to notify user. again few people use $http different way like
this.getMovie = function(movie) {
return $http.get('/api/v1/movies/' + movie)
.then(
function (response) {
return {
title: response.data.title,
cost: response.data.price
});
},
function (httpError) {
// translate the error
throw httpError.status + " : " +
httpError.data;
});
};
here then is using.......is it promise sample ? why people would then instead of success ? what is the advantage of then ?
what is the meaning of promise and what promise does ?
when to use promise in angular ?
Per angular DOCS, looks like 1.4.4 is the first version to have the notice(see below).
Deprecation Notice
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
From the docs, the new preferred angular way to do all $http requests.(code from angular docs)
General usage
The $http service is a
function which takes a single argument— a configuration object— that is used to generate an HTTP request and returns a promise.
// Simple GET request example :
$http.get('/someUrl').
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
// Simple POST request example (passing data) :
$http.post('/someUrl', {
msg: 'hello word!'
}).
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
SO resource
SO resource

Promise Chains in angularjs

I am uploading attachments using rest api in SharePoint 2013,for this I need to call upload attachment method on synchronous.
Because If I call upload attachment method asynchronous I am getting 409 conflict error.
How to chain promise objects in for loop.i.e I want to call second attachment method in first attachment success and so on..
Please help me in best approach of chaining of promises in for loop.
Common method for saving attachments:
var saveFileAngularJS = function (file, url) {
var deferred = $q.defer();
getFileBuffer(file).then(function (fileArrBuffer) {
$http({
method: 'POST',
url: baseUrl + url,
headers: {
'Accept': 'application/json;odata=verbose',
'Content-Type': undefined,
'X-RequestDigest': jQuery("#__REQUESTDIGEST").val()
},
data: new Uint8Array(fileArrBuffer),
transformRequest: []
}).then(function successCallback(data) {
deferred.resolve(data);
alert('Successfully saved.', data);
}, function errorCallback(error) {
deferred.reject(error);
alert('Failed to save!!!.', error);
});
});
return deferred.promise;
};
Method calling :
for (var i = 0; i < $scope.files.length; i++) {
var file = $scope.files[i]._file;
var response = lssDealService.insertAttachment(transactionId, file);
}
var insertAttachment = function (dealId, file) {
var attachmentUrl = listEndPoint + "/GetByTitle('TransactionList')/GetItemById(" + dealId + ")/AttachmentFiles/add(FileName='" + file.name + "')";
return baseService.saveFile(file, attachmentUrl);
};
Insert attachment will call SaveFile method.
I want to run this for loop sequentially, once the loop has been completed I need to process all promises and display success message to user.
Please help me to writing the chaining promises in effective way.
Lets say you have the attachements as an array,
function uploadMyAttachements() {
return myAttachements.reduce(function(promise, attachment) {
return promise.then(function () {
return upload(attachment);
})
.then(function(result) {
console.log('RESULT FOR LAST UPLOAD', result);
});
}, Promise.resolve());
}
function upload(attachment) {
//upload the attachment to sharepoint
//and return a promise here
}
uploadMyAttachements().catch(function(err) {
//if anything in the promise chain fails
//it stops then and there and CATCHED here
});
Now whats happening here, using the Array.reduce, we create a chain of promises like shown below
upload(0).then(handleResult_0).upload(1).then(handleResult_1)....
and it execute one by one as you expected
Throwing my 2 pennies:
$scope.attachments = []; //modified via binding.
function uploadAttachments(){
//Reduce the files array into a promise array with the uploadOne method
//then return the promise when every promise has been resolved or one has rejected.
return $q.all($scope.attachments.reduce(uploadOne, []));
}
function uploadOne(file){
//Upload one, return promise. Use $http or $resource.
}
//Note - a more advanced way of doing this would be to send the files as batch (one
//$http post) as FormData. There are some good wrappers for angular.
$scope.upload = function(){
uploadAttachments().then(function(results){
//Array of results
}).catch(function(e){
//Error handler
});
}

$http.get doesn't work with REST model using then() function

As you guys know, Angular recently deprecated the http.get.success,error functions. So this kind of calls are not recommended in your controller anymore:
$http.get("/myurl").success(function(data){
myctrl.myobj = data;
}));
Rather, this kind of calls are to be used:
$http.get("/myurl").then(
function(data) {
myctrl.myobj = data;
},
function(error) {
...
}
Problem is, simple Spring REST models aren't working with this new code. I recently downloaded a sample code with the above old success function and a REST model like this:
#RequestMapping("/resource")
public Map<String,Object> home() {
Map<String,Object> model = new HashMap<String,Object>();
model.put("id", UUID.randomUUID().toString());
model.put("content", "Hello World");
return model;
}
This should return a map like {id:<someid>, content:"Hello World"} for the $http.get() call, but it receives nothing - the view is blank.
How can I resolve this issue?
The first (of four) argument passed to success() is the data (i.e. body) of the response.
But the first (and unique) argument passed to then() is not the data. It's the full HTTP response, containing the data, the headers, the status, the config.
So what you actually need is
$http.get("/myurl").then(
function(response) {
myctrl.myobj = response.data;
},
function(error) {
...
});
The expectation of the result is different. Its the response and not the data object directly.
documentation says :
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).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.
});
Properties of the response are
data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
As the data object is required,
Please convert the code as
$http.get("/resource").then(
function(response) {
myctrl.myobj = response.data;
});
then must be return a new promise so you should handle it with defers.
var myApp = angular.module('myApp', []);
myApp.factory('modelFromFactory', function($q) {
return {
getModel: function(data) {
var deferred = $q.defer();
var items = [];
items.push({"id":"f77e3886-976b-4f38-b84d-ae4d322759d4","content":"Hello World"});
deferred.resolve(items);
return deferred.promise;
}
};
});
function MyCtrl($scope, modelFromFactory) {
modelFromFactory.getModel()
.then(function(data){
$scope.model = data;
})
}
Here is working fiddle -> https://jsfiddle.net/o16kg9p4/7/

Angular promise callback not firing

I have this app that uploads a file to a server using $cordovaFileTransfer and then sends data about the file to the same server. The file is transferred fine. The data is then sent to the server, and the server responds. But the response does not make it back to the promise callback. Why?
$scope.sendPost = function(data) {
//first upload a file then send more data about the file
$cordovaFileTransfer.upload('http://example.com', 'myfile.txt', options)
.then(function(result) {
var promise = MyFactory.sendFileData(data);
});
promise.then(function(response) {
//we never make it to here
});
}
and in MyFactory:
service.sendFileData = function(data) {
return $http({
//bunch of parameters. This function works, data is sent to the server and a response received
}).then(function(response) {
//this is fired when the response is received from the server. All is good so far.
return.response.data
});
}
return service;
$cordovaFileTransfer.upload returns a promise object, which you could use to build up promise chaining mechanism.
Code
$scope.sendPost = function(data) {
//get hold on `upload` function promise
var promise = $cordovaFileTransfer.upload('http://example.com', 'myfile.txt', options)
.then(function(result)) {
//return MyFactory.sendFileData promise here which will follow promise chaining
return MyFactory.sendFileData(data);
});
//promise.then will get call once `MyFactory.sendFileData` complete it
promise.then(function(response) {
//will get called once `sendFileData` complete its promise
});
}
its because you're relaying on another promise's callback to initiate a the promise and.. most probably before the promise gets initialized you are attaching a callback tot it.. so at the time of you attaching the callback, the promise is not yet initialized i.e. promise is null.. so in your console you'll see an error..
try doing some thing like
var x = function(response) {
//we'll make it to here now...
}
$cordovaFileTransfer.upload('http://example.com', 'myfile.txt', options)
.then(function(result)) {
var promise = MyFactory.sendFileData(data);
promise.then(x);
});
You should follow #PankajParkar solution though it's a better approach...
$scope.sendPost = function(data) {
//first upload a file then send more data about the file
$cordovaFileTransfer.upload('http://example.com', 'myfile.txt', options)
.then(function(result)) {
return MyFactory.sendFileData(result.data);
})
.then(function(response) {
});

How to get data from JSONP error callback in angularjs?

I am trying to get response message from jsonp error callback in angularjs, but response data is undefined. I return the response with 409 http code. If to open jsonp url directly in browser it shows "angular.callbacks._0({"message":"Reset link is incorrect"})", but I can't get this message in error callback. What am I doing wrong?
// Extend angular app for api requests
app.factory('User', function($http) {
var User = function(data) {
angular.extend(this, data);
};
// Send link for password reset to entered email
User.reset_password = function() {
return $http.jsonp(jsonp_url + 'user/reset_pass?_method=post&user_key=' + user_key + '&callback=JSON_CALLBACK');
};
return User;
});
app.controller('ResetPasswordController', function ResetPasswordController($scope, User){
$scope.submit = function() {
var response = User.reset_password();
response.then(function(data){
//Success callback
}, function(data){
// Error callback
console.log(data) // Output: {config : {...}, data: undefined}
});
}
});
As said Brandon Tilley it is not possible to get data from jsonp response with http error code. If you want anyways to get error message you need to send something like this {result: false, msg: 'Error occured...'} with "good" http code, for example 200.

Resources