"Can not read property" after an http.get request

4

Hello, how are you?

I have the following problem. I'm making a RESTful request (http.get) and I'm writing the received object into a variable within the $ scope. However, when I try to access this variable inside the controller I get the following error:

My controller:

.controller('chartEvapo', function($http, $scope) {
  $http.get(meurepositorio)
    .success(function(response) {
      angular.forEach(response, function(response) {
        $scope.cityOBJ = response;
      });
    });

    var teste = $scope.cityOBJ.info.etppri;
})

And the error:

  

Can not read property 'info' of undefined

What I find strange is that I can print the values as follows:

<div>
  {{cityOBJ.info.etppri}}
</div>

The return of console.log (response) is:

 Object{_id: Object, id:"1", info:Object"}
 _id: Object
 id: "1"
 info: Object
 __proto__: Object

EDIT:

With the following controller I had the following error:

.controller('chartEvapo', function($http, $scope) {
var teste;

$http
    .get(meurepositorio)
    .success(function(response) {
        $scope.cityOBJ = response;
        atualizaTeste();
    });

// está função ira atualizar a variável teste para você
function atualizaTeste() {
    this.teste = $scope.cityOBJ.info.etppri;
}
});
  

TypeError: Can not read property 'etppri' of undefined       at updateTest (controllers.js)

EDIT 2: With JSON.stringify;

  function atualizaTeste() {
    console.log(JSON.stringify($scope.cityOBJ));
    this.teste = $scope.cityOBJ.info.etppri;
}

Return on console:

  

["id": {"$ oid": "5807a914dcba0f490c71818b"}, "id": "1", "info": {"etppri": [10,112,10,112,10,14,10,112,10,155,142, 50], "etppen": [10, 11, 12, 132, 3, 2, 80, 60, 55, 22, 112 "," 15 "]," etptho ": [" 10 "," 11 "," 12 "," 132 "," 3 "," 2 "," 80 "," 60 "," 55 " "30", "30", "30", "30", "30", "20", "80", " 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30 "," 35 "," 22 "," 30 "," 35 "]}}}]

    
asked by anonymous 20.10.2016 / 04:48

2 answers

3

Renan, use your controller in this way to see if it will solve the problem.

.controller('chartEvapo', function($http, $scope) {
    var teste;

    $http
        .get(meurepositorio)
        .success(function(response) {
            $scope.cityOBJ = response;
            atualizaTeste();
        });

    // está função ira atualizar a variável teste para você
    function atualizaTeste() {
        this.teste = $scope.cityOBJ[0].info.etppri;
    }
});

I'm thinking that maybe the error happens because $http and angular.forEach are asynchronous

    
20.10.2016 / 19:42
2

This happens because the object returned in callback has several properties. The one that interests you is data , which contains the body of the returned response.

Change your code as follows:

$scope.cityOBJ = response.data;

You can find more information about the response object here .

    
20.10.2016 / 14:44