I have a question, seeking advice, on how to get data that is stored in service arrays to the controller since unwrapping promises was removed in 1.2.
Example:
- Route one contains a list of items
- Route two contains a form to add a new item
- Once the item was saved from route tow, user is redirected back to route one.
When route one initially loaded, the service would make a request to the server for the items, store the items in an array in the service so every request for route one after that would just return an array. When an item was saved, that item was pushed to the array in the service.
If I were to wait for the promise in route one's controller on the initial load, no problem because a response was sent back, but every request to route one after that would return an error because I was returning an array.
Any ideas on how to accomplish something like this in 1.2?
app.factory('Items',function($http) {
var items = [];
return {
list: function() {
if (items.length == 0) { // items array is empty so populate it and return list from server to controller
return $http.get('/?items').then(function(response) {
items = response.data.items;
return response.data.items;
});
}
return items; // items exist already so just return the array
},
save: function(item) {
return $http.post('/',{item:item}).then(function(response) {
items.push(item);
return response;
});
}
}
});
app.controller('RouteOne',function($scope,Items) {
Items.list().then(function(response) {
$scope.items = response;
});
/* used to be this before unwrapped promises were removed
$scope.items = Items.list();
*/
});
app.controller('RouteTwo',function($scope,Items) {
$scope.new_item = {};
$scope.addItem = function() {
Items.save($scope.new_item).then(function(response) {
$location.path('/'); // back to route one
});
};
});