Let's say I have an array of books that I GET from an endpoint like /api/books
.
[{
name: 'Book 1',
id: 1
}, {
name: 'Book 2',
id: 2
}, {
name: 'Book 3',
id: 3
}]
I have a BookService that retrieves the categories for an individual book. For example, this makes a request to /api/book/:id/categories
.
BookService
function BookService($resource) {
var service = $resource('/api/books', {}, {
getAll: {
method: 'GET'
},
getCategories: {
url: '/api/book/:id/categories',
method: 'GET',
isArray: true
},
});
return {
getAll: getAll,
getCategories: getCategories
};
}
In my route, I have a resolve (using ui-router) that gets all books first and is injected into the BookCtrl
:
resolve: {
books: ['BookService', function(BookService) {
return BookService.getAll();
}]
}
In my example controller, I want to augment the books
resolve result with each book's categories. So for example, I want books
to be something like the following for my controller:
[{
name: 'Book 1',
id: 1,
categories: ['adult', 'horror']
}, {
name: 'Book 2',
id: 2,
categories: ['scifi']
}, {
name: 'Book 3',
id: 3,
categories: ['comedy']
}]
How can I create an additional resolve (or use the already existing one) to accomplish this?
resolve: {
books: ['BookService', function(BookService) {
return BookService.getAll();
}],
bookCategories: ['BookService', 'books', function(BookService, books) {
// this doesnt work
_.each(books, function(book) {
BookService.getCategories(book.id)
.then(function(categories) {
book.categories = categories;
})
});
// how do i return this to the controller properly?
}],
}
function BookCtrl(books, bookCategories) {
// maybe somsething like this?
var booksWithCategories = _.extend(books, bookCategories);
}