AngularJS: UI Router resolve with $resource

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
$stateProvider
.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(post.id).$promise;
}
});

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


Comments

Leave a Reply

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

To respond on your own website, enter the URL of your response which should contain a link to this post’s permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post’s URL again. (Find out more about Webmentions.) 要在你自己的网站上回应,请输入你的回应页面的 URL,该页面应包含指向此文章永久链接 URL 的链接。你的回应随后将显示在此页面上(可能需要经过审核)。想更新或删除你的回应?请更新或删除你的文章并再次输入你的文章 URL。(了解更多关于 Webmention 的信息。) 自分のサイトで返信するには、この投稿のパーマリンク URL へのリンクを含む返信ページの URL を入力してください。あなたの返信は(承認後に)このページに表示されます。返信を更新または削除したい場合は、あなたの投稿を更新または削除し、再度その投稿の URL を入力してください。(Webmention について詳しくはこちら。)