Recently, I've been delving into AngularJS and trying to create a function that deletes a user. The goal is to have the function return a boolean value indicating whether the deletion was successful or not.
Despite my best efforts, the promise always resolves to true even when the API response indicates failure. I followed advice from various sources like this one: Return value from a promise in Angular, but couldn't find a solution.
In my user controller file (user.controller.js), the code looks like this:
deleteUser(user) {
const self = this;
self.userActionPromise = self.userService.deleteUser(user.id).then(deleted => {
if (deleted) {
self.messagesService.successMessage('user.DELETE_SUCCESS');
self.loadUsers();
} else {
self.messagesService.errorMessage('user.DELETE_FAILURE');
}
});
}
And in my user REST service file (user.rest.service.js), here's what it contains:
self.user = $resource(config.restServerUrl + 'users/:id', {id: '@id'}, {
delete: {method: 'DELETE'}
});
deleteUser(id) {
return this.user.delete({id: id}).$promise.then(deleted => {
return !!deleted;
});
}