AngularJS: UI Router resolve with $resource

This article is last updated over 6 years ago, the information mentioned may be changed or developed.

Long time no see! It really has been long since last time I post on this topic. That’s because I’ve been working on the “real New 1A23”, I was rewriting the entire CMS on my own. Front-end and back-end. Anyway, this time, there’s a my solution to one of the problems I found: Compatibility between ui-router‘s resolve and $resource.

0x0: What’s happening?

UI-Router is a famous routing module for single-page app routing with AngularJS. In its state manager, the resolve feature allows external resources, especially AJAX requests to be loaded in dependence order before the view is rendered. However, in the official documentation, only examples for $http is given. If you tried to return a the result of $resource directly, you will find that the controller is actually called before the external resource is resolved. For those resource that depends on others, it will just fail silently.

0x1: Why is that so?

UI-router utilising AngularJS’s Promise object to manage and process async requests, and enqueue it in a queue. For any requests that is done async-ly, it should return a promise object in the resolve tree.

0x2: So how to solve it?

It’s simple, you can return .$promise from the resource request. Example code:

.state('demo', {
url: '/demo',
template: '<h1>Demo page</h1>',
controller: 'DemoController',
resolve: {
post: ["PostAPI", function (PostAPI) {
return PostAPI.get().$promise;
comments: ["post", "CommentAPI", funciton (post, CommentAPI) {
return CommentAPI.get($promise;

Yes, as simple as that. BTW, Jitaku works like a charm!

Leave a Reply

Your email address will not be published. Required fields are marked *