Reputation: 3072
Trying to get JSON data from an API and show the result in a view using AngularJS. I'm able to get the data correctly but unable to show it in the view. When i try to access the object's data the result is always undefined.
Here's what i'm doing...
API Service:
myApp.service('apiService', ['$http', function($http)
{
var api = "http://domain.xpto/api/";
var self = this;
this.result;
var apiService =
{
getSection: function(id)
{
var url = api + "section/" + id;
return $http.get(url);
}
}
return apiService;
}]);
Controller:
myApp.controller('mainController', ['$scope', '$routeParams', 'apiService', function($scope, $routeParams, apiService)
{
apiService.getSection(1).then(function(response)
{
$scope.$applyAsync(function ()
{
var data = response.data; //json data as expected
var section = data.section; //undefined?!
var images = data.images; //undefined!?
$scope.title = section.title; //undefined!?
});
});
}]);
UPDATE: Simplified my apiService based on @Salih's and @elclanrs's suggestion.
Why am i unable to access the inner objects of the json (f.e, data.section.title)?
UPDATE #2: I'm finally able to access the data. It seems i needed an extra data level to get access to the section object of my json array (response.data.data.section). Honesty i don't understand why. I've accessed the API using jquery and it was strait forward...
Upvotes: 0
Views: 398
Reputation: 468
Edit: I made this plunker to help you! http://embed.plnkr.co/Yiz9TvVR4Wcf3dLKz0H9/
If I were you, I would use the service function to update the own service value. You already created this.result
, you can just update its value.
Your Service:
myApp.service('apiService', ['$http', function($http)
{
var api = "http://domain.xpto/api/";
var self = this;
this.result = {};
this.getSection = function(id){
var url = api + "section/" + id;
$http.get(url).then(function(res){
self.result = res;
});
}
}]);
I wouldn't use a Promise for this case. You can access the Service's var into your Controller and View.
Your controller:
myApp.controller('mainController', ['$scope', '$routeParams', 'apiService',
function($scope, $routeParams, apiService)
{
$scope.apiSer = apiService;
$scope.apiSer.getSection(1);
}]);
In your View:
<pre>{{ apiSer.result }}</pre>
And now you'll see your parameter get updated in real time.
Upvotes: 1
Reputation: 315
You might need to use angular.forEach
method to parse your inner values of the JSON . Take a look at this example Accesing nested JSON with AngularJS
Upvotes: 1
Reputation: 2330
In your getSection function just write and return the following
return $http.get(url);
Upvotes: 1