AngularJS Route Resolve Failed Promise Example
In the previous post I looked at how the resolve property of an AngularJS route can be used to pass dependencies to a controller. In that example the resolve property in the route configuration called a service that returned a promise. The resolve property then passes the result of the promise to the controller when it is instantiated. The question that came up is what if there is an error and the promise is rejected instead of resolved? That's what I'll be answering in this post. The full example with a failed promise is in this plunk.
The route configuration from the previous post is below.
$routeProvider.when('/', {
templateUrl: 'greetingTemplate.html',
controller: 'greetingCtrl',
resolve: {
greeting: function(greetingService){
return greetingService.getGreeting();
}
}
});
So what happens if the promise returned by grettingService.getGreeting() is rejected instead of resolved? I found that the route doesn't work and the page is never loaded. A call to the 'then' function needs to happen inside the route configuration as highlighted below.
$routeProvider.when('/', {
templateUrl: 'greetingTemplate.html',
controller: 'greetingCtrl',
resolve: {
greeting: function(greetingService){
return greetingService.getGreeting().then(function(success) {return success;}, function(failure){
console.log("Failed");
return failure;
});
}
}
});
When the above is used the route will still resolve and print "Failed" to the console as well as inject the rejected promise data into the controller when it's instantiated. As you can see, it's possible to handle rejected promises but the route configuration needs to look for both resolved and rejected and explicitly return the result.