I am trying to refactor some code out of my controller and into the route's 'resolve' and am having trouble getting the correct return value from resolve. I think the problem is either due to my misunderstanding of js closures or the $q library in angular.
In the routing:
.when('/countries/:id', {
templateUrl: 'country/country.html',
controller: 'countryCtrl',
resolve: {
ActiveCountry: ['CountryData', '$q', '$route', function(CountryData, $q, $route) {
var defer = $q.defer();
CountryData($route.current.params.id).then(function(data){
console.log(data);
defer.resolve(data);
});
return defer.promise;
}]
}
})
The console.log in this block returns the correct JSON object from the api call. However, when it is passed into the controller, the controller returns the function from the CountryData service:
.controller('countryCtrl', [
'CountryData',
'$routeParams',
'$scope',
function (ActiveCountry, $routeParams, $scope) {
var countryId = $routeParams.id;
console.log(ActiveCountry);
$scope.mapId = $routeParams.id.toLowerCase();
$scope.country = ActiveCountry;
}
]);
The value of the routing console.log is:
Object {countryName: "Spain", currencyCode: "EUR", fipsCode: "SP", countryCode: "ES", isoNumeric: "724"…}
but the controller console log is the function from my CountryData service:
function (countryId) {
var defer = $q.defer();
$http.get(COUNTRIES_PATH + '&country=' + countryId + API_AUTH, { cache: true }).success(function (data) {
defer.resolve(data.geonames[0]);
});
return defer.promise;
}
Why is the object from the routing not being passed into the controller correctly?
Also, why do I need to use $q in the router when it is already built into the CountryData service? Without using $q in the routing, it returns the function rather than the function's return value.
why do I need to use $q in the router when it is already built into the CountryData serviceYou don't have to. Just make CountryData return promise.