问题
I am a new to AngularJS area and I am trying to use it with ASP.NET Web API. I am struggling right now with the Delete Function. The user should be able to delete an item from a list of items and when he deletes an item successfully, the list should be updated (or refreshed) immediately after that deletion. I already implemented the deletion function, however, the list doesn't get updated after the deletion and I don't know why.
Here's the code of deletion function in Web API:
// DELETE api/<controller>/5
public void Delete(int id)
{
itemRepository.DeleteItem(id);
}
And here's the AngularJS Controller Code:
app.controller('itemsController', ['itemsFactory', 'itemFactory', function (itemsFactory, itemFactory) {
var vm = this;
vm.message = "Welcome to Items Page";
vm.Items= itemsFactory.query();
// callback for ng-click 'deleteItem':
vm.deleteItem = function (aId) {
itemFactory.delete({ id: aId });
vm.Items= itemsFactory.query();
};
}]);
And here's the AngularJS Service Code:
app.factory('itemsFactory', function ($resource) {
return $resource('/api/items', {}, {
query: { method: 'GET', isArray: true },
create: { method: 'POST' }
})
});
app.factory('itemFactory', function ($resource) {
return $resource('/api/items/:id', {}, {
show: { method: 'GET' },
update: { method: 'PUT', params: { id: '@id' } },
delete: { method: 'DELETE', params: { id: '@id' } }
})
});
So how can I get the list of items updated immediately after any successful deletion operation?
回答1:
That's because itemFactory.delete in your case is $resource object which run asynchronously. So the problem is in this rows:
// callback for ng-click 'deleteItem':
vm.deleteItem = function (aId) {
// You send request to the server
itemFactory.delete({ id: aId });
// You don't get response from the server yet, so your item hasn't deleted.
vm.Items= itemsFactory.query();
};
So to accomplish that all you need is update your vm.Items inside itemFactory.delete callback like this:
vm.deleteItem = function (aId) {
itemFactory.delete({ id: aId }, function () {
// Update your items after you get success response from the server after deleting
vm.Items= itemsFactory.query();
});
};
来源:https://stackoverflow.com/questions/30291116/how-to-refresh-the-list-of-items-after-deleting-one-item-using-angularjs