Search code examples
angularjsngresource

Sending id to DELETE API using $resource in angularJS


I have this delete method with $resource for my angularJS service,

return $resource(apiUrl, {}, {
    delete: {
        url: apiUrl+ ":itemId",
        params: { itemId: "@itemId" },
        method: 'DELETE'
    }
});

However while trying to call the delete method, the request which sends from the service is without itemId.

dataService.delete({ itemId: itemId}, {})
                .$promise
                .then((data) => {
                    // Statements
                })
                .catch((error) => {
                    // Logging
                })
                .finally(() => {});

The URL supposed to call is https://url:someport/v1.0/items/{itemId} However the current url is https://url:someport/v1.0/items

Is there a way to get this doe using the current $resource code?


Solution

  • I think you need to use second parameter to specify params for the request.

    return $resource(apiUrl, {itemId: '@itemId'}, {
    delete: {
        method: 'DELETE'
    }
    });
    

    You can see entire documentation over here https://docs.angularjs.org/api/ngResource/service/$resource . This will give you better idea. You need to provide params in second argument (object).

    var User = $resource('/user/:userId',
    {userId: '@id'},
    {delete: {
        method: 'DELETE' }
    });
    
    User.delete({userId: 123}).$promise.then(function(user) {
      // perform other operations
    });