Imran Imran - 1 month ago 7
AngularJS Question

How to read array object in angularjs

I got this array objects to be read:

enter image description here

These was my sample codes:

$scope.obj_qst_local_study_main = tbl_qst_local_study_main.all();
$scope.quesion_id_allocated = $scope.obj_qst_local_study_main[0];
$timeout(function(){
console.log('----------all objects----------');
console.log($scope.obj_qst_local_study_main);
console.log('-----------one object-----------');
console.log($scope.quesion_id_allocated);
},200);


When I used:

$scope.obj_qst_local_study_main[0];


The result was:
undefined





My angularjs services:

.service('tbl_qst_local_study_main', function($cordovaSQLite, DATABASE_LOCAL_NAME){
var self = this;
var qst_local_study_main_array = [];
self.all = function() {
var db = $cordovaSQLite.openDB({name: DATABASE_LOCAL_NAME,location:'default'});
$cordovaSQLite.execute(db, "SELECT * FROM qst_local_study_main")
.then(function (res) {
console.log('--------Successfully read from qst_local_study_main---------');
for (var i = 0; i < res.rows.length; i++) {
qst_local_study_main_array.push(res.rows.item(i));
}
},
function (err) {
console.log(err);
});
return qst_local_study_main_array;
};
})

Answer

Your service should return a Promise. This is a super common case, because (don't be offended please) people do not understand how Promises work.

Please search the internet for an article, like this one: https://developers.google.com/web/fundamentals/getting-started/primers/promises

tl;dr Your service should return a Promise. In your case $cordovaSQLite.execute Then you can correctly handle the response by chaining thens. You also do not need the timeout. Using a timeout is super bad here!

tbl_qst_local_study_main.all()
  .then(function(result) {
    console.log(result);
  })
Comments