I have a factory method which looks like below:
angular.module('GridSamplesApp')
.factory('registerPostFactory', function($resource, $q, WebRequest) {
var getMessage = function(Upddata, token, dataurl)
{
var deferred = $q.defer();
var settings = {
data: Upddata,
headers: {
'Content-Type': 'application/JSON',
'x-csrf-token' : token
},
method: 'POST',
url: dataurl,
withCredentials: true
};
WebRequest.requestRaw(settings).then(
function(response) {
// data from app sec
var msg = response;
deferred.resolve(msg);
},
function(error) {
console.log('Error retrieving message', error);
deferred.reject('Error retrieving message', error);
});
return deferred.promise;
};
return {
getMessage: getMessage
};
});
I have a controller which looks like
$scope.getLogs = function()
{
$.each($scope.modifiedSN, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
$scope.inputs.push({SN:'', Key:'', status:'', log:''});
for(var i=0; i<result.length; i++)
{
var j = result[i];
if ($scope.data[j].SerialNumber !== "")
{
var Upddata = {};
Upddata['IConvRuleFlg'] = '';
Upddata['SrNum'] = $scope.data[j].SerialNumber;
Upddata['LvEmailId'] = 'abc@xyz.com';
Upddata['WKey'] = $scope.data[j].WtyKey;
registerPostFactory.getMessage(Upddata, $scope.token, dataurl).then(
function(response) {
$scope.msg = response.headers["custommessage"];
$scope.data[j].AutolinkErrorlog = $scope.msg;
$scope.inputs.push({SN: $scope.data[j].SerialNumber, Key: $scope.data[j].WtyKey, status: response.headers["msgtype"], log: $scope.msg});
},
function(error) {
console.log('Error reading msg: ', error);
}
);
}
}
};
The issue with this is that it only takes the last element in the array since it is an asynchronous call and the loop will not wait for the response, I tried using $q.all()
but could not figure out how to implement this, can anyone please help?