exports.getFbFriendsFromFbIdAndFbAccessTokenTest=function(id,token){
var request = require('request');
var urls = "https://graph.facebook.com/" + id + "/friends?access_token=" + token;
request(urls, function(error, response, body) {
if (!error && response.statusCode == 200) {
var output = JSON.parse(body);
output.sort(function(a,b){
if (a.name > b.name)
return 1;
if (a.name < b.name)
return -1;
// a must be equal to b
return 0;
});
console.log(output);
}
});
}
I want to sort the facebook friend's list in ascending order. Currently i am getting the following result in console:
`{ data: `
[ { name: 'xxx', id: '547dsad1' },
{ name: 'xxx', id: '55324iii' },
{ name: 'xxx', id: '55yyy' },
........
........
But it gives error that object output has no property sort.
I have also used Array.prototype:
Array.prototype.sortByProp = function(p){
return this.sort(function(a,b){
return (a[p] > b[p]) ? 1 : (a[p] < b[p]) ? -1 : 0;
});
}
output.sortByProp('name');
But then it shows the same error that object output has not property sortByProp.
Is there any other way to solve this problem?
output is an object, output.data is an array
Array.prototype.sortByProp = function(p){
return this.sort(function(a,b){
return (a[p] > b[p]) ? 1 : (a[p] < b[p]) ? -1 : 0;
});
};
console.log(output.data.sortByProp('name'));
Related
I'm trying to create a service that return me the NgTableParams so I don't need to do it every time I need a table.
I was able to do it and it worked, but only if i have only one table using it in my controller, if I try to use it in a second table look's like the service mess the parameters of the fist and second table and stop working.
I tried to change the service to a factory and tried to make a angular.copy of the service so each copy create one different table yet noting worked.
Every time i need a table it is like this:
$scope.tableParams = NgTableDataService.getGenericTableParams($scope.onboardcomputerstatus, $scope.filterObject);
$scope.searchTable = { filter: '' };
$scope.tableParams = new NgTableParams({
count: $scope.session.user.tablePagination,
filter: $scope.searchTable.filter
}, {
counts: rowsPerPageTemplate,
getData: function (params) {
var funcFilter = function (item) {
var pfilter = params.filter().filter.toUpperCase();
return item.onboardComputer.id.toString().indexOf(pfilter) >= 0
|| (!!item.onboardComputer.remainingMonitoringMsgs ? item.onboardComputer.remainingMonitoringMsgs : "").toString().indexOf(pfilter) >= 0
|| $filter('date')((!!item.onboardComputer.oldestMonitoringTimestamp ? item.onboardComputer.oldestMonitoringTimestamp : ""), Session.get().company.dateHourFormatHTML).indexOf(pfilter) >= 0
|| $filter('date')((!!item.lastCommunicatio ? item.lastCommunicatio : ""), Session.get().company.dateHourFormatHTML).indexOf(pfilter) >= 0
|| $filter('date')((!!item.lastRegister ? item.lastRegister : ""), Session.get().company.dateHourFormatHTML).indexOf(pfilter) >= 0
|| item.vehicle.code.toUpperCase().indexOf(pfilter) >= 0
|| item.vehicle.name.toUpperCase().indexOf(pfilter) >= 0;
}
filteredData = params.filter() ? $filter('filter')($scope.onboardcomputerstatus, funcFilter) : $scope.onboardcomputerstatus;
if (!!filteredData && filteredData.length >= 0) {
params.total(filteredData.length);
var rowsPerPageTemplateWithAllData = rowsPerPageTemplate.slice();
var isFound = rowsPerPageTemplateWithAllData.some(function (element) {
return element === filteredData.length;
});
var filteredDataLength = filteredData.length + (isFound ? 1 : 0);
rowsPerPageTemplateWithAllData.push(filteredDataLength);
params.settings().counts = rowsPerPageTemplateWithAllData;
if (params.count() === MY_CONSTANTS.TABLE_PAGINATION_ALL) {
params.count(filteredDataLength);
}
if (params.total() <= params.count()) {
params.page(1);
}
var x = $filter('orderBy')(filteredData, params.orderBy());
var y = x.slice((params.page() - 1) * params.count(), params.page() * params.count());
return y;
} else {
return null;
}
}
});
So I tried to do a factory like this:
angular.module('control-room').factory('NgTableDataFactory', function (
$filter, MY_CONSTANTS, NgTableParams, Session
) {
var ngTableObj = {};
ngTableObj.tableData = {};
ngTableObj.filterObject = {};
ngTableObj.session = Session.get();
ngTableObj.defaultDateFormat = (!!ngTableObj.session.company ? ngTableObj.session.company.dateHourFormatHTML : null);
ngTableObj.tablePagination = (!!ngTableObj.session.user ? ngTableObj.session.user.tablePagination : MY_CONSTANTS.QTD_REG_TAB_INDEX);
ngTableObj.NgTableParamsFactory = new NgTableParams({
count: ngTableObj.tablePagination,
filter: ""
}, {
counts: rowsPerPageTemplate,
getData: function (params) {
if (!!params.filter().filter && params.filter().filter != '') {
var pfilter = params.filter().filter.toUpperCase();
} else {
var pfilter = '';
}
let filteredData = params.filter() ? $filter('filter')(ngTableObj.tableData, ngTableObj.funcFilterFactory(ngTableObj.filterObject, pfilter)) : ngTableObj.tableData;
if (!!filteredData && filteredData.length >= 0) {
params.total(filteredData.length);
var rowsPerPageTemplateWithAllData = rowsPerPageTemplate.slice();
var isFound = rowsPerPageTemplateWithAllData.some(function (element) {
return element === filteredData.length;
});
var filteredDataLength = filteredData.length + (isFound ? 1 : 0);
rowsPerPageTemplateWithAllData.push(filteredDataLength);
params.settings().counts = rowsPerPageTemplateWithAllData;
if (params.count() === MY_CONSTANTS.TABLE_PAGINATION_ALL && filteredDataLength > 0) {
params.count(filteredDataLength);
}
var x = $filter('orderBy')(filteredData, params.orderBy());
var y = x.slice((params.page() - 1) * params.count(), params.page() * params.count());
return y;
} else {
return null;
}
}
});
ngTableObj.findPropertyValue = function (obj, propertyList){
let aux = obj;
for(property of propertyList){
aux = aux[property];
}
return aux
};
ngTableObj.funcFilterFactory = function (f_Object, p_filter) {
return function (item) {
var result = false;
if (!!f_Object.columnNames) {
f_Object.columnNames.forEach(function (row) {
if (!result){
const propertyValue = ngTableObj.findPropertyValue(item, row.split('.'));
result = (propertyValue ? propertyValue.toString() : "").toUpperCase().indexOf(p_filter) >= 0 || result;
}
});
};
if (!!f_Object.translateNames) {
f_Object.translateNames.forEach(function (row) {
if (!result){
const propertyValue = ngTableObj.findPropertyValue(item, row.split('.'));
result = $filter('translate')((propertyValue != null ? propertyValue.toString() : "").toUpperCase()).indexOf(p_filter) >= 0 || result;
}
});
}
if (!!f_Object.dateFormat) {
f_Object.dateFormat.forEach(function (row) {
if (typeof(row) == 'string') {
if (!result) {
const propertyValue = ngTableObj.findPropertyValue(item, row.split('.'));
result = propertyValue ? $filter('date')(propertyValue, ngTableObj.defaultDateFormat).toUpperCase().indexOf(p_filter) >= 0 : false || result;
}
}else {
if (!result) {
const propertyValue = ngTableObj.findPropertyValue(item, row[0].split('.'));
result = propertyValue ? $filter('date')(propertyValue, row[1]).toUpperCase().indexOf(p_filter) >= 0 : false || result;
}
}
});
}
return result;
};
};
return ngTableObj
});
and in the controller is like this:
$scope.filterObject = {
columnNames : ['onboardComputer.id', 'onboardComputer.remainingMonitoringMsgs', 'vehicle.code', 'vehicle.name' ],
dateFormat : ['onboardComputer.oldestMonitoringTimestamp', 'lastCommunicatio', 'lastRegister' ]
};
$scope.tableFactory = NgTableDataFactory;
$scope.tableFactory.tableData = $scope.onboardcomputerstatus;
$scope.tableFactory.filterObject = $scope.filterObject;
$scope.tableFactory.session = Session.get();
$scope.tableParams = $scope.tableFactory.NgTableParamsFactory
Like I said, this way it work well, but only if i use one time, if I have 2 tables it stop working
I'm trying to remove a value from an array in my database which I get from url.
I use the code below but I get nothing. It doesn't go to the for loop.
app.get('/remove/:medid/:tokenid', function(req, res) {
var medid = req.params.medid;
var token = req.params.tokenid;
var query = { tokenid: token, mediaid !== 'undefined' && mediaid.length > 0 }
user.find(query).exec(function(err, result) {
if (err) {
res.send('erooooooor')
}
if (!result) {
res.send('whooops, you dont have any media yet :)')
} else {
console.log('its here')
for (var i in result.mediaid) {
console.log(i)
if (i == medid) {
user.update({ tokenid: token }, { $pull: { mediaid: medid } }, function(err, result2) {
if (err) {
res.send('an error happened')
} else {
console.log('deleted')
//res.send('your tokenid is '+ token)
}
})
} else {
res.send('media id didnt match')
}
}
}
});
});
My database has 3 objects userid and tokenid which are strings and mediaid which is an array.
Also, I want to check if my mediaid array is null or not and exist is this code
mediaid !== 'undefined' && mediaid.length > 0
You have got your json syntax incorrect in following line
var query = {tokenid: token, mediaid !== 'undefined' && mediaid.length > 0}
You should probably just let your query be based on token id.
var query = {tokenid: token};
Also when you write for(var i in result.mediaid), for each iteration of loop, the variable 'i' is assigned the index of current element, not its value. So your if condition should be modified to check result.mediaid[i] == medid instead of i == medid. Modified loop should look something like:
for(var i in result.mediaid){
console.log(i);
if(result.mediaid[i] === medid){
user.update({tokenid: token}, {$pull: {mediaid: medid}},function(err, result2){
if (err){
res.send('an error happened');
}
else{
console.log('deleted');
//res.send('your tokenid is '+ token)
}
});
}
}
Please, you can replace to:
app.get('/remove/:mediaid/:tokenid', function(req, res){
var medid = req.params.mediaid;
var token = req.params.tokenid;
var query = {tokenid: token, mediaid !== 'undefined' && mediaid.length > 0}
UPDATED:
I recommended that print after console.log(medid, token);
I hoped help you - Jose Carlos Ramos
The below code is working for me to get data on API calls but I have one question here. Every time it creates elements in DOM and populate the data which we get from API. But if I get lesser records it is showing blank/empty records. How can I remove or stop generating those blank records?
this.infiniteItems = {
numLoaded_: 0,
toLoad_: 0,
items: [],
getItemAtIndex: function (index) {
if (index > this.numLoaded_) {
this.fetchMoreItems_(index);
return null;
}
return this.items[index];
},
getLength: function() {
return this.numLoaded_ + 25;
},
fetchMoreItems_: function (index) {
if (this.toLoad_ < index) {
this.toLoad_ += 5;
var offset = 0;
$http({
method: 'GET',
datatype: 'json',
url: '{my-api-call}',
contentType: "application/json; charset=utf-8",
cache: false,
params: {
param: query,
page: offset
}
}).then(angular.bind(this, function (obj) {
this.items = this.items.concat(obj.data.SearchResults);
this.numLoaded_ = this.toLoad_;
this.offset++;
$scope.searchResults = obj.data.SearchResults;
}));
}
}
};
Thanks in advance.
I had the same problem and I solved it like this:
$scope.infiniteBrands = {
numLoaded_: 0,
toLoad_: 0,
items: [],
page: -1,
hasMoreItems: true,
perPage: 7,
//REQUIRED.
getItemAtIndex: function(index) {
if (index > this.numLoaded_) {
this.fetchMoreItems_(index);
return null;
}
return this.items[index];
},
//REQUIRED
getLength: function() {
return this.numLoaded_ + 1;
},
fetchMoreItems_: function(index) {
if ( this.hasMoreItems && (this.toLoad_ < index)) {
this.page++;
this.toLoad_ += this.perPage;
brandsFactory.getBrands(this.perPage, this.page)
.then(angular.bind(this, function (data) {
this.items = this.items.concat(data);
if(data.length < this.perPage){
this.numLoaded_ = this.toLoad_ - (this.perPage - data.length) -1;
this.hasMoreItems = false;
}else{
this.numLoaded_ = this.toLoad_;
}
}))
.catch(function(errorResponse){
console.log('Error in brands controller, status : ', errorResponse.status);
});
}
}
};
As you can see the lines that prevents the empty rows are:
if(data.length < this.perPage){
this.numLoaded_ = this.toLoad_ - (this.perPage - data.length) -1;
this.hasMoreItems = false;
}else{
this.numLoaded_ = this.toLoad_;
}
where this.perPage are the number of items I want to ask per page but if the server returns me a lower number, because there are no more, I need to substract those from the this.numLoaded_ variable.
Its late but I hope it helps to anyone who had the same problem.
You should check if your API call has reached the lastPage.
fetchMoreItems_: function (index) {
if ((this.toLoad_ < index) && !this.lastPage) {
this.toLoad_ += this.size;
newsActions.getNews(this.page++, this.size).then(angular.bind(this, function (newsData) {
this.items = this.items.concat(newsData.content);
this.numLoaded_ = this.toLoad_ >= newsData.totalElements ? newsData.totalElements : this.toLoad_ ;
this.lastPage = newsData.last;
}));
}
}
Then use it in getLength function:
getLength: function () {
if(this.lastPage){
return this.numLoaded_
}
return this.numLoaded_ + 2;
},
Hi i need to do this two http get...after that i need to put data in tables and show it...but unfortunately angular doesn't wait the http request. How can i do that? in this code?
Many thanks in advance.
$rootScope.chiamataUno = function() {
var authdata = Base64.encode("DEMVSINT_ADMIN" + ":" + "Password01");
$http.defaults.headers.common["Authorization"] = "Basic " + authdata;
$http.get('http://demvsint-as1-sd.services.eni.intranet:8001/CaseManager/P8BPMREST/p8/bpm/v1/queues/DV_ResponsabileBSDL/workbaskets/Responsabile BSDL/queueelements/?cp=DCMSVS_CONN1').success(function(response) {
console.log(response);
$rootScope.rispostaUno = response.queueElements;
$rootScope.risposta = response;
$rootScope.responseJSON = JSON.stringify($scope.risposta);
var newArray = [];
$rootScope.newObjectJSON = [];
$scope.newObject = [];
for(var i=0;i<response.queueElements.length;i++){
var newObject = {
//forse togliere elementi e columns
//elementi:response.queueElements[i],
caseFolderId:response.queueElements[i].caseFolderId.replace("{","").replace("}",""),
caseTaskId:response.queueElements[i].caseTaskId.replace("{","").replace("}",""),
stepName:response.queueElements[i].stepName,
columns:response.queueElements[i].columns,
DV_Caseidentifier_for_eni_OdA: response.queueElements[i].columns.DV_Caseidentifier_for_eni_OdA,
DV_EBELP_ODA: response.queueElements[i].columns.DV_EBELP_ODA,
DV_EINDT_ODA: response.queueElements[i].columns.DV_EINDT_ODA,
DV_MATNR_TXZ01_POS_ODA: response.queueElements[i].columns.DV_MATNR_TXZ01_POS_ODA,
DV_NAMECL_POS_ODA: response.queueElements[i].columns.DV_NAMECL_POS_ODA,
DV_NETPR_WAERS_POS_ODA: response.queueElements[i].columns.DV_NETPR_WAERS_POS_ODA,
DV_PEINH_POS: response.queueElements[i].columns.DV_PEINH_POS,
DV_MENGE_MEINS_POS_ODA: response.queueElements[i].columns.DV_MENGE_MEINS_POS_ODA
};
//console.log("data "+ newObject.DV_EINDT_ODA);
var dataHold = [];
if((newObject.DV_EINDT_ODA !== null) && (newObject.DV_EINDT_ODA !== "?")){
dataHold = newObject.DV_EINDT_ODA;
dataHold = dataHold.split("/");
var dataCorrect = dataHold[2] + "/" + dataHold[1] + "/" + dataHold[0];
//console.log("dataCorrect "+ dataCorrect);
}else{
dataCorrect = newObject.DV_EINDT_ODA;
}
$rootScope.newObjectJSON.push(JSON.stringify(newObject));
//console.log("rootScope.newObjectJSON " + $rootScope.newObjectJSON);
//console.log("dettaglio " + newObject.DV_MENGE_MEINS_POS_ODA + " " + newObject.stepName + " " + newObject.DV_EINDT_ODA);
//console.log("rootScope.caseFolderId " + newObject[i].caseFolderId + " "+ newObject[i].stepName);
newArray.push(newObject);
var queryOdl = "INSERT INTO Tabella_OdL_Temp (caseFolderId, caseTaskId, stepName, DV_Caseidentifier_for_eni_OdA,DV_EBELP_ODA,DV_EINDT_ODA,DV_MATNR_TXZ01_POS_ODA,DV_NAMECL_POS_ODA,DV_NETPR_WAERS_POS_ODA,DV_PEINH_POS,DV_MENGE_MEINS_POS_ODA, Approvata, Rifiutata, Archiviata) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$cordovaSQLite.execute(db, queryOdl, [newObject.caseFolderId === null ? "null" : newObject.caseFolderId.replace("{","").replace("}",""), newObject.caseTaskId === null ? "null" : newObject.caseTaskId.replace("{","").replace("}",""),newObject.stepName === null ? "null" : newObject.stepName, newObject.DV_Caseidentifier_for_eni_OdA === null ? "null" : newObject.DV_Caseidentifier_for_eni_OdA,newObject.DV_EBELP_ODA === null ? "null" : newObject.DV_EBELP_ODA, dataCorrect === null ? "null" : dataCorrect , newObject.DV_MATNR_TXZ01_POS_ODA === null ? "null" : newObject.DV_MATNR_TXZ01_POS_ODA,newObject.DV_NAMECL_POS_ODA === null ? "null" : newObject.DV_NAMECL_POS_ODA,newObject.DV_NETPR_WAERS_POS_ODA === null ? "null" : newObject.DV_NETPR_WAERS_POS_ODA,newObject.DV_PEINH_POS === null ? "null" : newObject.DV_PEINH_POS,newObject.DV_MENGE_MEINS_POS_ODA === null ? "null" : newObject.DV_MENGE_MEINS_POS_ODA, 0, 0, 0]).then(function(result) {
console.log("insert");
}, function(error) {
console.error(error);
});
}//fine for response.queueElements
//console.log(newObject[2]);
for(var j = 0; j < newArray.length; j++){
if(newArray[j].stepName !== "Item details"){
var casefolderId = newArray[j].caseFolderId.replace("{","").replace("}","");
chiamatadue.push('http://demvsint-as1-sd.services.eni.intranet:8001/CaseManager/CASEREST/v1/case/'+ casefolderId +'?TargetObjectStore=CM_DCMSVS_TGT_OBJ');
}
}
$rootScope.chiamataDueNuova();
}) .error(function(response) {
alert("ERROR");
});
}
> Blockquote
var index = 0;
$rootScope.chiamataDueNuova = function(){
if(chiamatadue.length > 0 && index < chiamatadue.length){
var authdata = Base64.encode("DEMVSINT_ADMIN" + ":" + "Password01");
$http.defaults.headers.common["Authorization"] = "Basic " + authdata;
//inserire le autorizzazioni per la chiamata
$http.get(chiamatadue[index]).success(function(result){
index = index + 1;
console.log(result);
$scope.objJ = result.Properties;
var objToInsertOnDB = {
caseFolderId: "",
DV_EBELN_ODA: "",
DV_AEDAT_ODA: "",
DV_EKGRP_EKNAM_ODA: "",
DV_NAME_ODA: "",
DV_NETPR_WAERS_ODA: "",
DV_NAME_CR: "",
DV_StatoPraticaOdA: "",
DV_Caseidentifier_for_eni_OdA: "",
DateCreated: "",
DV_Caseidentifier_for_eni_OdA: ""
};
for(var i = 0; i < $scope.objJ.length; i++){
var actualObj = $scope.objJ[i];
//Ricerco gli elementi da trasmettere nella tabella Chiamata2
if(actualObj['SymbolicName'] === 'DV_EBELN_ODA'){
objToInsertOnDB['DV_EBELN_ODA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_AEDAT_ODA") {
objToInsertOnDB['DV_AEDAT_ODA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_EKGRP_EKNAM_ODA") {
objToInsertOnDB['DV_EKGRP_EKNAM_ODA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_NAME_ODA") {
objToInsertOnDB['DV_NAME_ODA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_NETPR_WAERS_ODA") {
objToInsertOnDB['DV_NETPR_WAERS_ODA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_NAME_CR") {
objToInsertOnDB['DV_NAME_CR'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_StatoPraticaOdA") {
objToInsertOnDB['DV_StatoPraticaOdA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_Caseidentifier_for_eni_OdA") {
objToInsertOnDB['DV_Caseidentifier_for_eni_OdA'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DateCreated") {
objToInsertOnDB['DateCreated'] = actualObj['Value'];
} else if (actualObj['SymbolicName'] === "DV_Caseidentifier_for_eni_OdA") {
objToInsertOnDB['DV_Caseidentifier_for_eni_OdA'] = actualObj['Value'];
}
}
//setto nell'oggetto il caseFolderId
objToInsertOnDB['caseFolderId'] = chiamatadue[index-1].replace("http://demvsint-as1-sd.services.eni.intranet:8001/CaseManager/CASEREST/v1/case/","").replace("?TargetObjectStore=CM_DCMSVS_TGT_OBJ","");
console.log("caseFolderId " + objToInsertOnDB.caseFolderId);
console.log("DV_AEDAT_ODA " + objToInsertOnDB['DV_AEDAT_ODA']);
console.log("DV_NAME_CR " + objToInsertOnDB['DV_NAME_CR']);
console.log("DV_StatoPraticaOdA " + objToInsertOnDB['DV_StatoPraticaOdA']);
console.log("DV_EKGRP_EKNAM_ODA " + objToInsertOnDB['DV_EKGRP_EKNAM_ODA']);
var cfId = objToInsertOnDB.caseFolderId;
var queryOdl = "INSERT INTO Tab_OdL2_Temp(caseFolderId, DateCreated, DV_Caseidentifier_for_eni_OdA, DV_EBELN_ODA, DV_AEDAT_ODA, DV_EKGRP_EKNAM_ODA, DV_NAME_ODA, DV_NETPR_WAERS_ODA, DV_NAME_CR, DV_StatoPraticaOdA, Approvata, Rifiutata, Archiviata) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
$cordovaSQLite.execute(db, queryOdl, [objToInsertOnDB.caseFolderId === null ? "null" : objToInsertOnDB.caseFolderId, objToInsertOnDB.DateCreated === null ? "null" : objToInsertOnDB.DateCreated, objToInsertOnDB.DV_Caseidentifier_for_eni_OdA === null ? "null" : objToInsertOnDB.DV_Caseidentifier_for_eni_OdA,objToInsertOnDB.DV_EBELN_ODA === null ? "null" : objToInsertOnDB.DV_EBELN_ODA, objToInsertOnDB.DV_AEDAT_ODA === null ? "null" : objToInsertOnDB.DV_AEDAT_ODA, objToInsertOnDB.DV_EKGRP_EKNAM_ODA === null ? "null" : objToInsertOnDB.DV_EKGRP_EKNAM_ODA, objToInsertOnDB.DV_NAME_ODA === null ? "null" : objToInsertOnDB.DV_NAME_ODA, objToInsertOnDB.DV_NETPR_WAERS_ODA === null ? "null" : objToInsertOnDB.DV_NETPR_WAERS_ODA, objToInsertOnDB.DV_NAME_CR === null ? "null" : objToInsertOnDB.DV_NAME_CR, objToInsertOnDB.DV_StatoPraticaOdA === null ? "null" : objToInsertOnDB.DV_StatoPraticaOdA, 0, 0, 0]).then(function(result) {
console.log("insert Tab_OdL2_Temp");
}, function(error) {
console.error(error);
});
$rootScope.chiamataDueNuova();
});//fine get
}//fine if
$http.get("/your/url").then(function(response) {
// your code that does something with the response HERE
}).catch(function(failedResponse) {
// non-200 response from your HTTP call
})
this is because $http returns a promise. As with all promises, they have a then method which is executed when the promise is resolved or rejected.
If you have more than one request and want to act when all requests are complete you can chain them using $q. See the example below:
$q.all([one.promise, two.promise, three.promise]).then(function() {
console.log("ALL INITIAL PROMISES RESOLVED");
});
var onechain = one.promise.then(success).then(success),
twochain = two.promise.then(success),
threechain = three.promise.then(success).then(success).then(success);
$q.all([onechain, twochain, threechain]).then(function() {
console.log("ALL PROMISES RESOLVED");
});
I have a factory that calls 4 json files and then I want to do some treatmenet for each data from these files and push them into an array of objects this is the code I wrote :
myapp.factory('wordsCloudFactory', function($http) {
var factory = {
getList: function() {
return $http.get('data/periode_1_file.JSON')
.then(function(response1) {
return $http.get('data/periode_2_file.JSON')
.then(function(response2) {
return $http.get('data/periode_3_file.JSON')
.then(function(response3) {
return $http.get('data/periode_4_file.JSON')
.then(function(response4) {
var words = [{
'period1': [],
'period2': [],
'period3': [],
'period4': []
}];
console.log(words);
for (var i = response1.data['X_id'].length - 1; i >= 0; i--) {
words['period1'].push({
id: response.data['X_id'][i],
count: response.data['count'][i]
});
};
for (var i = response2.data['X_id'].length - 1; i >= 0; i--) {
words['period2'].push({
id: response.data['X_id'][i],
count: response.data['count'][i]
});
};
for (var i = response3.data['X_id'].length - 1; i >= 0; i--) {
words['period3'].push({
id: response.data['X_id'][i],
count: response.data['count'][i]
});
};
for (var i = response4.data['X_id'].length - 1; i >= 0; i--) {
words['period4'].push({
id: response.data['X_id'][i],
count: response.data['count'][i]
});
};
return words;
}, function(error) {
return 'There was an error getting data';
})
}, function(error) {
return 'There was an error getting data';
})
}, function(error) {
return 'There was an error getting data';
})
}, function(error) {
return 'There was an error getting data';
})
}
};
return factory;
})
this code it doesnt work it shows me an error message : 'Cannot read property 'push' of undefined'.
How can I solve this ?
As you can see in my code there are a lot of nested $http.get methodes isn't there another way to write that ?
Your words is an array of object
var words = [{
'period1': [],
'period2': [],
'period3': [],
'period4': []
}];
You have to access it by index.
Try like this
words[0]['period1'].push({
id: response.data['X_id'][i],
count: response.data['count'][i]
});
JSFIDDLE
If it's just an object Like
var words = {
'period1': [],
'period2': [],
'period3': [],
'period4': []
};
Then your push was ok .
words['period1'].push({
id: response.data['X_id'][i],
count: response.data['count'][i]
});
JSFIDDLE