I'm a beginner with AngularJS and I'm creating an application that retrieves data from an API.
The problem is: I don't know how to access the object that I'm returning or if there's a better way to do that.
service.js
app.factory('Service', ['$resource', '$q',
function($resource, $q) {
var City = $resource('http://localhost:8000/:action?:q_params', {
action: 'api/city/',
q_params: '@params',
}, {
get: {
method: "GET",
isArray : false,
transformResponse: function(data, headers){
response = {}
response.data = data;
response.headers = headers();
return response;
}
}
});
return {
citiesByCountry: function(country_id) {
defer = $q.defer();
var data = [];
City.get({'country_id': country_id}).$promise.then(function(response) {
data.push.apply(data, JSON.parse(response.data));
defer.resolve(response);
}).
catch(function(response) {
alert(response.data.detail);
defer.reject(response);
});
return data;
},
};
}]);
control.js
app.controller('Control', ['$scope', 'Service',
function($scope, Service) {
$scope.func = function() {
var cities = Service.citiesByCountry('123');
console.log(cities);
console.log(cities.length);
for (var item in cities) {
console.log(item.name);
}
};
}]);
When I call the function in the controller, the console.log prints:
Array [ Object ]
0
The object is there, apparently, but I don't know how to access it. I checked some questions and this one (Accessing objects returned from a factory) was good but it didn't solve my problem, because I cannot access the object yet.