2

I have a problem which should be wasy to solve, but I just cant figure out what I am doing wrong. I receive data through an $http request.

alert(data)

gives me object object

alert(data.response)

gives me {"id":"123456","post_id":"12345"}

alert (data.response.id)

gives me undefined

My question: I want to get the ID. Why does the last expression give me undefined and not the ID? Do I have to transform the data in some way?

I am thankful for any hints!

2
  • 2
    It means that data.response is a string, not an Object. Otherwise similarly to alert(data) you would have got [object Object]. Commented Nov 24, 2014 at 22:03
  • 2
    Your response is probably a string. You'll need to turn it into JSON first. Call the function angular.fromJson on $scope.data.response then you can call the id. Commented Nov 24, 2014 at 22:09

3 Answers 3

6

It looks like your data.response is a string. You use angular.fromJson to convert it to object ie :

$scope.temp = angular.fromJson($scope.data.response);

please see working demo below

var app = angular.module('app', []);

app.controller('firstCtrl', function($scope){
 $scope.data = {
 response:'{"id":"123456","post_id":"12345"}'
 };
  
  alert($scope.data);
  alert($scope.data.response);
  
   alert($scope.data.response.id);
  
  $scope.temp = angular.fromJson($scope.data.response);
  
  alert($scope.temp.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
  <div ng-controller="firstCtrl">

      </div>
</body>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Perfect answer and perfectly explained!
1
var app = angular.module('myApp', []);

app.controller('list_employeesController', function($scope, $http) {
  // email = $scope.email;
  // psw = $scope.psw;
  $http({
    method: "GET",
    url: "http://localhost:3000/employees",
    params: {}

  }).then(function mySuccess(response) {
      // a string, or an object, carrying the response from the server.
      $scope.myRes = response.data;
      $scope.statuscode = response.status;

    }, function myError(response) {
      $scope.myRes = response.statusText;
  });
});

Simply Here myRes has the response data to this request.

And we can display it in HTML file using expression syntax in angular

 <h2> Result : {{myRes}} </h2>

Comments

-1
var app = angular.module('myApp', []);

app.controller('student_Controller', function($scope, $http) {

  $http({
    method: "GET",
    url: "http://localhost:8000/employees",
  }).then(function mySuccess(response) {

      $scope.res= response.data;
      $scope.statuscode = response.status;

    }, function myError(response) {
      console.log("response--"+response);
  });
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.