I have declared a state using ui-router and am trying to perform a resolve. However, I cannot return a value in my resolve using a $http in a factory. Below is one way that I've tried.
It appears that the success callback runs too late so that nothing is actually returned inside the resolve. When the success callback does run, it produces the desired result.
...
.state('book', {
url: '/book',
abstract: true,
views: {
'': {
templateUrl: 'templates/book.html',
controller: bookController
}
}
})
.state('book.detail', {
url: '/{chapter}/{pageName}',
resolve: {
pageIdNumber: ['$http','$stateParams', 'myFactory', function($http, $stateParams, myFactory) {
return myFactory.getPageIdNumberUsingPageName(
function(response, $stateParams) {return response[0];}, // console.log(response[0]) gives the desired result but nothing is returned. I think this function runs too late.
function(response) {return response[0];},
$stateParams.pageName);
}]
},
views: {
'page@book': {
templateUrl: 'templates/page.html',
controller: pageController
}
}
})
...
myFactory.$inject = ['$http'];
function myFactory($http){
return {
getPageIdNumberUsingPageName: function (callbackSuccess, callbackError, pageName){
$http({
method: 'POST',
url: 'http://example.com/api/get_page_id.json',
cache: true,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
data: 'page_name=' + encodeURIComponent(pageName),
})
.success(function (response) {
callbackSuccess(response);
})
.error(function (response) {
callbackError(response);
});
}
};
}
promisebased setup for resolve to work. Callbacks do not work. See this video thinkster.io/egghead/resolve