angularjs - Restangular post in loop -
i need call list of restangular.post inside of loop, add many user (for example)
i have factory that:
createuser (user) { return restangular.all(url).post(user); }
then in controller in need call factory inside of loop:
for( var in users){ createuser(us); }
the problem cant this! add last user object!, how $q.all() using restangular, or there other solution??
okay problem small.
the problem call createuser function inside loop. loop continues execute post request not gets fulfilled. , hence last user object saved only.
so can do:
you have make recursive function when first objects saved call same function second object , on.
or
you can try callback function. please read first how callback function works.
here used callback function. may you.
function createuser(userobject, cb){ restangular .all(url) .post(user) .then(function (response){ if(response){ cb(null, response); //user created.. callback function }else{ cb(err, 'error occured'); } }) .catch(function(ex){ //something bad happened... }) } var index = 0; function save(){ if(users.length != index + 1){ createuser(users[index], function(data){ console.log(data); //this saved data return callback index++; }); } }
now need call save function only. here users array contains users object.
Useful information for students who on Angular JS training .
ReplyDelete