Kurkula Kurkula - 8 days ago 6
Javascript Question

angularjs get correct format data from service

I am trying to read values from json through angular and display data on UI. I am unable to do that because the format which I get to UI is not an array. When I added to console and see the format it is little different. I tried to to play with "c" in console and unable to play with the object. Any hint in how can I display {{details}} on my page?

enter image description here

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http, MyService) {

$scope.details = MyService.getDetails();
console.log($scope.details);

});
app.service('MyService', function ($http) {
this.getDetails = function (x, y) {

return $http.get("/Home/GetMyData")
.then(function (response) {
return response.data;
});
}
});


</script>

public JsonResult GetMyData()
{
var details = GetDet();
return Json(details, JsonRequestBehavior.AllowGet);
}

Answer

MyService.getDetails returns a promise and thus the code below only shows the promise object

$scope.details = MyService.getDetails();
console.log($scope.details); // promise object

You need to do this to get the resolved values of getDetails:

MyService
    .getDetails()
    .then(function(details){
        $scope.details = details;
        console.log($scope.details); // your array
    });

I hope this helps!

Comments