1

Hi I am developing web application in angularjs. I am trying to query array in angularjs. Below is my code snippet.

var angulararray = [];
bindleaselistings.bindleaselistingsmethod().then(function(response) {
  angular.forEach(response.data.data.LeaseList, function(value, key) {
    angulararray.push(value);
  });
}, function(error) {});
console.log(angulararray);
debugger;
var found = $filter('filter')(angulararray, {
  id: accountnumber
}, true);
if (found.length) {
  $scope.selected = JSON.stringify(found[0]);
} else {
  $scope.selected = 'Not found';
}

console.log displays required array. I have attached screenshot.enter image description here

When i debug the var found = $filter('filter')(angulararray, { id: accountnumber }, true); I can see angulararray is empty. May I know am I doing anything wrong in above code? Any help would be appreciated. Thank you

Niranjan Godbole
  • 2,135
  • 7
  • 43
  • 90

3 Answers3

2

The problem is with asynchronous execution of your code.The execution of your API call and the code below it, will be executed in parallel. The value of angulararray is empty outside the API call. You can move your filtering inside the success callback of your API.

var angulararray = [];
bindleaselistings.bindleaselistingsmethod().then(function(response) {
    angular.forEach(response.data.data.LeaseList, function(value, key) {
        angulararray.push(value);
    });
var found = $filter('filter')(angulararray, {
    id: accountnumber
}, true);
}, function(error) {});
console.log(angulararray);

if (found.length) {
    $scope.selected = JSON.stringify(found[0]);
} else {
    $scope.selected = 'Not found';
}
Vivz
  • 6,625
  • 2
  • 17
  • 33
1

You're having an async problem. Your code needs to be run after the promise is resolved.

The reason you get the response in the console.log is because your tools show a live view of the variable. So once the variable is resolved the view in the console will change to the result of the resolved promise.

var angulararray = [];
bindleaselistings.bindleaselistingsmethod().then(function (response) {
    angular.forEach(response.data.data.LeaseList, function (value, key) {
        angulararray.push(value);
    });
    console.log(angulararray);
    debugger;
    var found = $filter('filter')(angulararray, {
        id: accountnumber
    }, true);
    if (found.length) {
        $scope.selected = JSON.stringify(found[0]);
    } else {
        $scope.selected = 'Not found';
    }
}, function (error) { });
Tim
  • 1,606
  • 2
  • 21
  • 42
0

you could change the way u filter ur variable and have something like this:

 var found;
 var len = angulararray.length;
 for(var i=0; i<angulararray; i++){
  if(typeof angulararray[i]['AccountNumber'] === 'undefined') {
    $scope.selected = 'Not found';
  }
  else {
  found = angulararray[i];
  $scope.selected = JSON.stringify(found[0]);
  }
 }