Struggling to retrieve JSON data from an API and display it in a view using AngularJS. Although I am able to fetch the data correctly, I am facing difficulties in showing it in the view. Whenever I try to access the object's data, I constantly receive undefined as the result.
Here is the approach I am taking...
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 retrieved successfully
var section = data.section; //Why is this undefined?
var images = data.images; //Still undefined
$scope.title = section.title; //Remains undefined
});
});
}]);
JSON Result: https://i.sstatic.net/CtKKB.jpg
UPDATE: Modified my apiService based on suggestions from @Salih and @elclanrs.
What could be causing the inability to access the nested objects of the JSON (e.g., data.section.title)?
UPDATE #2: Managed to finally access the data by adding an extra data level to reach the section object in my JSON array (response.data.data.section). Honestly, I am still puzzled about why this was necessary. Accessing the API with jQuery was much simpler...