0
votes

Suppose I have some data in firestore. When I call the "Calculation" Function then for each matched element "alld" array is pushed with new objects. After push(), I get, console.log(alld); It is ok. But when I call getBl() function, and console.log(alld.n); then it shows all the data, and also showing Error: "TypeError: Cannot read property 'n' of undefined at b.$scope.getBl". I could not understand the reason. I know get() is an asynchronous function. I also applied $scope.$applyAsync();. Is this the reason, or there exist some other reason, I don't know. What could be the solution?

var app = angular.module('myApp', ['firebase', 'ngRoute', 'angular.filter']);

app.controller('mCntlr', function ($scope, $firebaseArray) {
  var alld=$scope.alld=[{'n':j,'d':h,'c':l}];
  
  
 $scope.getBl=function (b){
let i=0;
   for(i=0;i<alld.length;i++)
   console.log("check  = "+$scope.alld[i].n); //Consol.log is printing data but it also showing "TypeError: Cannot read property 'n' of undefined"
   };
   
   
   $scope.Calculation = function (e) { firebase.firestore().collection("DataCollection").get()
  .then(function (snapshot) {

    snapshot.docs.forEach(element =>{
       fld =element.data();
       fld.dC.forEach(function(item){ alld.push({'n':item.A,'d':dr,'c':c});
  $scope.$applyAsync();});

     });
         console.log(alld); //it is ok
         $scope.getBl(); 
  }).catch(function (err) {
    console.log(err);
  });
  };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
1
for(i=0;i<alld.length;i++) console.log("check = "+$scope.alld[i].n); Before this for loop, If I write, console.log(alld.length); then it is also showing the length ! Its really confusing ! - SoftDev

1 Answers

0
votes

Try using this

 console.log("check  = "+alld[i].n);

As the values of those objects (n,d,c) were undefined you were getting this error. Or instead of using let i=0; try using var i=0; and instead of using var alld=$scope.alld=[{'n':j,'d':h,'c':l}]; try using $scope.alld=[{'n':j,'d':h,'c':l}]; then you must have to write console.log($scope.alld);