I find myself running into a few circular dependency issues among my services, which probably means they're just built incorrectly.
The basics - this works fine:
.factory('bookCollection', function($http, urls, user) {
var books = [];
return {
data: books,
getBooks: getBooks,
reset: resetCollection,
addBook: addToCollection
};
///////////////////////////////////
function getBooks() {
var params = {
user: user.current
};
return $http.get(urls.getBooks, { params: params })
.then(function(res) {
books = res.data;
return books;
});
}
function resetCollection() {
books = [];
}
function addToCollection(book) {
books.push(book);
persistCollection(books);
}
function persistCollection(books) {
return $http.post(urls.postBooks, books)
.then(function(res) {
return res.status;
});
}
})
.factory('user', function($http, urls) {
var currentUser = {};
return {
current: currentUser,
getUser: fetchCurrentUser
};
///////////////////////////////////
function fetchCurrentUser(userId) {
return $http.get(urls.getUser, { params: { id: userId }})
.then(function(res) {
angular.copy(res.data, currentUser);
});
}
});
Now I want to introduce the ability to reset the current bookCollection
when I fetch a new user. But if I add bookCollection
as a dependency to user
then I will have created a circular dependency.
How else can I make this bookCollection.reset
process automatic so that every time I fetch a new user I wipe the collection?
Also, as a side note, I'm wondering if my bookCollection.data should be its own service separate from the methods that interact with the server, since one is just a "store" for the data and the other is a communication layer.