angularjsspringspring-mvcangularjs-ng-resource

how to delete record in spring mvc using angularjs request


frontend code

    <button data-ng-click="deleteRec()" id="Delete">delete</button>
        var app = angular.module('myApp', ['ngResource']);
 app.controller('UserController', ['$scope', '$resource',function($scope,$resource) 
    {
             $scope.deleteRec = function()
                     {
                        User = $resource(
                                'delete/:username',
                                 {method:'DELETE', params: {username: '@username'}});
                        User.delete({username: $scope.myform.username}).then(function successCallback(response) 
                        {
                            $scope.Message = response;
                        }, function errorCallback(response) {

                        });

                        $scope.myform.username = "";
                        $scope.myform.phone="";
                        $scope.myform.email="";
                        $scope.myform.address="";
                        $scope.myform.password=""; 
                      };
}]);

controller code

@RequestMapping(value="/delete/{username}")
    public @ResponseBody String delete(@PathVariable("username") String username) 
    {
        String user=retrievedataservice.delete(username);
        return null;
    }

error came like this TypeError: User.delete(...).then is not a function Actually, User is a object and delete() method to pass the parameter in spring Controller method delete().


Solution

  • As I refereed with the docs,

    User.delete is a Class action return an empty instance (with one of the additional properties below)

    $promise: The promise of the original server interaction that created this instance or collection.

    So you need to call the $promise of the instance.

     var app = angular.module('myApp', ['ngResource']);
     app.controller('UserController', ['$scope', '$resource',function($scope,$resource) 
        {
                 $scope.deleteRec = function()
                         {
                            User = $resource(
                                    'delete/:username',
                                     {method:'DELETE', params: {username: '@username'}});
                            User.delete({username: $scope.myform.username}).$promise.then(function successCallback(response) 
                            {
                                $scope.Message = response;
                            }, function errorCallback(response) {
    
                            });
    
                            $scope.myform.username = "";
                            $scope.myform.phone="";
                            $scope.myform.email="";
                            $scope.myform.address="";
                            $scope.myform.password=""; 
                          };
    }]);