Save response from $http service to an array in angularjs - javascript

Following is the code, which is consoling the response but unable to set the response to store in $scope.dateWiseData array. Let me know what I am doing wrong.
$scope.dateWiseData = [];
var tmpArr = [];
var x = 0;
for (var i=0; i< 7;i++) {
$http.post('/api/getdata', {_id: currentUser._id, data: data}).then(function(response){
console.log(response.data);
tmpArr.push(response);
if ( x < 7 ) {
$scope.dateWiseData = tmpArr;
}
x++;
});
}
console.log("--Week Data Array--");
console.log($scope.dateWiseData);

if you try to print the console.log($scope.dateWiseData); this will execute before the $scope.dateWiseData array is assigned to data which means this will print before the data is getting from server. but your data should be assigned to that array after the http is completes. You need to check the promises in javascript
$scope.getData() = function(){
var deferred = $q.defer();
for (var i=0; i< 7;i++) {
$http.post('/api/dayavailability', {_id: SessionService.currentUser._id, weekDay: new Date($scope.sevenWeekDayArr[i]).toISOString()}).then(function(response){
tmpArr = response.data;
if ( x < 7 ) {
$scope.dateWiseData.push(tmpArr);
}
if(x==6) {
deferred.resolve();
}
x++;
});
}
return deferred.promise;
}
wrapt that for loop like this
and
$scope.getData().then(function() {
// processing
});
** Dont forget to add $q in as a parameter in the controller **

Related

Another Parse 'success/error not called' error

I recently posted an issue I had with another Parse CloudCode method, were the error was thrown that Error: success/error was not called. I am having that issue again but with a different method/scenario.
Parse.Cloud.define("background", function(request, response) {
var moments = require("cloud/moments.js");
var now = moments.moment();
var query = new Parse.Query("Group");
query.find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
var events = object.get("Events");
var getUsers = false;
for (var q = 0; q < events.length; q++) {
var e = events[q];
if (e.get("date") == now) {
getUsers = true;
break;
}
}
if (getUsers == true) {
for (var q = 0; q < events.length; q++) {
var e = events[q];
if (e.get("date") == now) {
var relation = object.relation("created");
var partOne = e.get("name");
var outString1 = partOne.concat(" is now");
// generate a query based on that relation
var query = relation.query();
Parse.Push.send({
where: query, // Set our Installation query
data: {
alert: outString1
}
}, {
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}
});
var relation2 = object.relation("joined");
var partOnee = e.get("name");
var outString = partOnee.concat(" is now");
// generate a query based on that relation
var query2 = relation.query();
Parse.Push.send({
where: query2, // Set our Installation query
data: {
alert: outString
}
}, {
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}
});
e.destroy();
}
}
}
}
}
});
response.success();
});
Since this method involves more than just a simple query and return (as it has the for loop among other things) I am a bit confused on how to implement the Parse Promise stuff. If anyone could assist me in how I should go about implementing the promise stuff it would be much appreciated.
Parse documentation is very clear on how to use Promises and how to rewrite your pyramid code with .then() blocks instead.

How can I append json data if object key is equal to a predefined value?

I have got an ajax GET request that pulls in data through a loop. What I am trying to achieve is to get posts that are relevant but are not in the predefined id value of the current post you are on. So I have this function below:
var _permId = $('#work-area').data('current-id');
var getRelatedPosts = function() {
$.ajax({
url: '/wp-json/posts?type=case-studies&filter[taxonomy]=awards&filter[term]='+_awardsPart+'',
success: function ( query ) {
//List some global variables here to fetch post data
// We use base as our global object to find resources we need
// _permId is the var that tells me the current id of this post
var posts = query;
postFull = [];
for(var i = 0; i < posts.length; i++) {
//terms.push(term);
var postObject = posts[i];
postFull.push(postObject);
for (var key in postObject) {
//console.log(postObject[key]);
if (postObject[key] === _permId) {
console.log('this is the same as this post');
}
}
};
},
cache: false
});
};
What I want to do is not allow any content through if the post object id is the same value as _permId.
Here is an idea of the json that is retrieved with keys and values:
Object {ID: 4434, title: "new brand case", status: "publish", type: "case-studies", author: Object…}
The ID is the value I want to set an argument against.
You haven't to loop on the object if you just want to check the ID :
...
postFull = [];
for(var i = 0; i < posts.length; i++) {
var postObject = posts[i];
postFull.push(postObject);
if(postObject.ID === _permId) {
//they have the same id
}
};
EDIT :
To get the datas you want you can use $.grep :
var newArray = $.grep(posts, function(e, i){return e.ID !== _permiId;});
or in pure JS
var newArray = [];
for(var i = 0; i < posts.length; i++){
var p = posts[i];
if(p.ID !== _permId){
newArray.push(p);
}
}

How to use $.when when the number of getJSON URLs is variable?

I'm chaining getJSON requests with .when.
Code is similar to this:
$.when( $.getJSON(url0),$.getJSON(url1), $.getJSON(url2)).done( function() {
$.each(arguments, function(index, result) { …
How can I write this so if the URL set contains url3 or url4 or more or only url0 it can proceed?
I store the url vars in a file or in local storage.
var list = ['obj1', 'obj2', 'obj3', 'obj4', 'obj5'];
var callback = function() {
console.log("done");
};
var requests = [];
for(i = 0; i < list.length; i++) {
requests.push($.ajax({
url: 'url',
success: function() {
console.log('suc');
}
}));
}
$.when.apply(undefined, requests).then(function(results){callback()});
You can give me some more details so i can load that in array and can show you how that works
JSFIDDLE DEMO : http://jsfiddle.net/MBZEu/4/
or you can try
var urlArr = ['url1', 'url2', 'url3', 'url4', 'url5'];
var callback = function() {
console.log("done");
};
var requests = [];
for(i = 0; i < urlArr.length; i++) {
requests.push($.getJSON(urlArr[i])); //or something similar which can push url in array
}
$.when.apply(undefined, requests).then(function(results){callback()});
or use this to see whats going on with req
requests.push($.getJSON(urlArr[i], function(res){console.log(res)}));

Why my jquery .get() result could not show by order i give

I am trying to make a google shortener analytic tools by javascript, it's my code:
<script>
function makeRequest() {
for (var i=0; i < shortUrl.length; i++){
var url = shortUrl[i];
var request = gapi.client.urlshortener.url.get({
'shortUrl': url,
'projection':'FULL',
});
request.execute(function(response) {
console.log(response); //here is the problem begin
var result = {
short: response.id,
clicks: response.analytics.allTime.shortUrlClicks
};
appendResults(result, i);
});
}
}
function load() {
gapi.client.setApiKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
gapi.client.load('urlshortener', 'v1', makeRequest);
}
</script>
<script src="https://apis.google.com/js/client.js?onload=load"></script>
the result would me different everytime!
ex:
shortUrl[1,2,3,4]
it will return 3,2,1,4 or 1,2,4,3......etc
what's wrong is my code?
is the async problem? how could i fix it?
please help me!
thx
Because ajax is asynchronous. You have to use promises.
jQuery example.
var promises = [];
for (var i=0; i < shortUrl.length; i++){
var dfd = new $.Deferred;
var url = shortUrl[i];
var request = gapi.client.urlshortener.url.get({
'shortUrl': url,
'projection':'FULL',
});
request.execute((function(dfd){return function(response) {
dfd.resolve(response);
};})(dfd));
promises.push(dfd.promise());
}
$.when.apply($, promises).done(function(){
promises = undefined;
for(var i in arguments){
var response = arguments[i];
console.log(response); //here is the problem begin
var result = {
short: response.id,
clicks: response.analytics.allTime.shortUrlClicks
};
appendResults(result, i);
}
});
My working code:
var promises = [];
var request = function(i, callback){
setTimeout(function(){return callback(i);},100 - i);
}
for (var i=0; i < 10; i++){
var dfd = new $.Deferred;
request(i, (function(dfd){return function(response) {
dfd.resolve(response);
};})(dfd));
promises.push(dfd.promise());
}
$.when.apply($, promises).done(function(){
promises = undefined;
for(var i in arguments){
console.log(arguments[i]);
}
});

How can I update data in a for loop when my data is returned with a defer after the loop completes

I have two arrays:
$scope.grid.data and $scope.grid.backup
I use the following script to compare the data in each one element at a time:
for (var i = 0, len = $scope.grid.data.length; i < len; i++) {
if (!angular.equals($scope.grid.data[i], $scope.grid.backup[i])) {
var rowData = $scope.grid.data[i]
var idColumn = $scope.entityType.toLowerCase() + 'Id';
var entityId = rowData[idColumn];
entityService.putEntity($scope.entityType, entityId, $scope.grid.data[i])
.then(function (result) {
angular.copy(result, $scope.grid.data[i]);
angular.copy(result, $scope.grid.backup[i]);
}, function (result) {
alert("Error: " + result);
})
}
}
and the following to update the database:
putEntity: function (entityType, entityId, entity) {
var deferred = $q.defer();
EntityResource.putEntity({ entityType: entityType, entityId: entityId }, entity,
function (resp) {
deferred.resolve(resp);
}, function (resp) {
deferred.reject('Error updating');
});
return deferred.promise;
}
This script correctly notices the changes and updates the database.
However there is a problem when the putEntity returns with a result and it then tries to copy the result into $scope.grid.data[i] and
$scope.grid.backup[i]
This happens later and when it tries to do this it always tries to put it into element 11.
Does anyone have any ideas how I can ensure the returned data from putEntity is copied back into the correct element of the grid.data and grid.backup arrays?
You need to create a closure over i. What you can do is create a function
var updateGridData=function(entityType, entityId, gridDataToUpdate, gridIndex)
entityService.putEntity(entityType, entityId,gridDataToUpdate)
.then(function (result) {
angular.copy(result, $scope.grid.data[gridIndex]);
angular.copy(result, $scope.grid.backup[gridIndex]);
}, function (result) {
alert("Error: " + result);
})
}
So your main method becomes
for (var i = 0, len = $scope.grid.data.length; i < len; i++) {
if (!angular.equals($scope.grid.data[i], $scope.grid.backup[i])) {
var rowData = $scope.grid.data[i]
var idColumn = $scope.entityType.toLowerCase() + 'Id';
var entityId = rowData[idColumn];
updateGridData($scope.entityType, entityId, $scope.grid.data[i],i);
}
}
You can get some more idea from this question JavaScript closure inside loops – simple practical example

Categories

Resources