Google+

Wednesday, July 22, 2020

#17 - How to send HTTP DELETE Requests from a SPA to an OData RESTful Web API

In this article we review How to send HTTP DELETE Requests from a SPA to an OData RESTful Web API,  to erase items using a web service, by developing from scratch in 30 minutes an AngularJS SPA (Single Page App) Application that sends HTTP GET, HTTP POST, HTTP PATCH and HTTP DELETE Requests to Add, Edit, and Delete the items from and to a REST OData Web API. Also, all style will be Twitter Bootstrap CSS3.
The source code for this SPA can be found in the following GitHub repository:


Although you can learn this tutorial as a standalone,  also you can see the previous lessons of the series, using the arrows below. This is the Lesson #17 in the "AngularJS: From 0 To 100" articles written for Beginners. This lessons start at Lesson #1   .

<<<<  PREVIOUS LESSON                              NEXT LESSON >>>>


This is a snapshot of the SPA AngularJS that we'll develop from scratch here, in 30 minutes  :

How to send HTTP DELETE Requests from a SPA to an OData RESTful Web API



How to send HTTP DELETE Requests from a SPA to an OData RESTful Web API


As we move forward through this Tutorial, we'll give you the source code to copy-paste to your project. In addition to that,  you can download the entire AngularJS SPA App from the following GitHub repository, all together packed in a ZIP file:



First we add the link references to the javascripts and styles  , using  CDN(content delivery network), instead of downloading the files to our project:

How to send HTTP DELETE Requests from a SPA to an OData RESTful Web API     1

As you see, we add 2 AngularJS scripts, and 2 Bootstrap CSS3 files. Also, we create directories for "Content" and "Controllers". It's important that you have the "angular.js" and ALSO the "angular-route.js" javascript files loaded.
Now, because this is a tutorial about sending HTTP DELETE requests to an OData REST Web API, we'll use the AngularJS SPA  that we built together in 20 minutes through the previous tutorial  Lesson #16  , and that already supports  Create, Read and Update functionality.
We'll add to it the AngularJS "Delete" functionality. That SPA already includes retrieving, adding and editing items by sending HTTP GET, POST and PATCH requests to an OData REST service. So please go back to the Lesson #16 , if you do not have an SPA app already working.

After you have the SPA app with Create, Read and Update functionality working, open the OrchidsList.html file , and add a new Bootstrap icon next to the "Edit" one, as follows:


How to send HTTP DELETE Requests from a SPA to an OData RESTful Web API      2


<a href="#/delete/{{Orchid.BlogID}}">
                             <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
   </a>

I've remarked the more relevant code in red. The two link buttons do load the "Edit" and the "Delete" View Templates, using the Bootstrap's Glyphicons.
This links send the ID of the selected item to the Edit or the Delete Controllers.

Next, we're going to code the AngularJS Module, and set the Routing to support also the "Delete" option, as follows:

How to send HTTP DELETE Requests from a SPA to an OData RESTful Web API      3


   .when('/delete/:id',
        {
            templateUrl: "/App/Views/OrchidsDelete.html",
            controller: "OrchidsDeleteCtl"
        })

Here we are using the  AngularJS $routeProvider to connect each View with the correspondent Template and  Controller.  If the "/delete" page is required, then the "OrchidsDelete.html" URL template will be displayed, and the "OrchidsDeleteCtl" Controller will be loaded.
This is always the same main HTML web page being browsed here, since this is a SPA application: all belongs to THE SAME URL: there are no web page reloads at all!!!


Finally, we add the "Delete" functionality to our SPA application, by creating a new View template called OrchidsDelete.html, containing this markup:
How to send HTTP DELETE Requests from a SPA to an OData RESTful Web API   4


<div class="container">
<div class="jumbotron">
    <div class="" >    
        <h2>Delete this Orchid</h2>  
    </div> 
        <form name="deleteOrchid" class=""
            data-ng-submit="fnDelete()">
            <input type="text" class="form-control"
            placeholder="Title"
            data-ng-model="Orchid.Title"
            disabled>
            <input type="text" class="form-control"
            placeholder="Text"
            data-ng-model="Orchid.Text"
            disabled>
            <input  data-ng-model="Orchid.MainPicture"  
                class="form-control" 
                disabled/> 
            <input type="submit" class="btn btn-default  btn-lg"
            value="Delete"
            data-ng-disabled="fnDisable()" ><span>&nbsp;{{fnShowMsg()}}</span>
        </form>
    
    <a href="#/">See All Flowers</a>
</div>
    </div>

As you see, all fields are read-only this time.

Also, we add a new Controller, for the "deleting" functionality:

How to send HTTP DELETE Requests from a SPA to an OData RESTful Web API    5


oOrchidsApp.controller('OrchidsDeleteCtl',
    ['OrchidsResource', 'GlobalSvc', '$http', '$routeParams', '$scope', '$location', '$log', 'msg',
        function (OrchidsResource, GlobalSvc, $http, $routeParams, $scope, $location, $log, msg) {

            msg.value = "";
            $scope.isDisabled = false;
            $scope.Orchid = OrchidsResource.get({ id: $routeParams.id });    

            $scope.fnDelete = function () {

                $http(
                {
                    url:  GlobalSvc.getURL() + $routeParams.id,
                    method:"DELETE"

                }
                ).success(function (response) {
                    msg.value = "Orchid successfully deleted";
                    $scope.isDisabled = true;
                }).error(function (err) {  $log.error(err); });
               
            }

            $scope.fnDisable = function () { return $scope.isDisabled;}

            $scope.fnShowMsg = function () { return msg.value; }


}]);


You can see here, that we first use the AngularJS $resource to fetch the data for the selected item, sending an HTTP GET(ID) request to the service. 
Then, when the user clicks the submit button, we send an HTTP DELETE request using the $http service that we inserted into the Controller at the Dependency Injection step.
Also, we add two methods: fnDisable() , to disable the submit button only if the response has been successfully received.
And fnShowMsg() , to display the corresponding message to the user.
Browse to the Main HTML web page, and click over the Bootstrap's "delete" icon:
How to send HTTP DELETE Requests from a SPA to an OData RESTful Web API    6



The Delete View will look as follows:


How to send HTTP DELETE Requests from a SPA to an OData RESTful Web API   7


Click the "Delete" button, and wait for the success message:

How to send HTTP DELETE Requests from a SPA to an OData RESTful Web API   8



If you get no response, or you get errors, check using the Developer's Tools (F12) in the "Network" tab, for the response status. If there is some error , refer to this HTTP Error Tutorial.


Remember to use widely the $log service in your SPA, to send yourself messages for debugging purposes.

That's All!!! You have started sending HTTP DELETE Requests to an OData Web API RESTful service,  from your own SPA application, using the AngularJS Dependency Injection for the $http, $log, and $routeParameters Services. In the next article we will put all the pieces together to  Create a SPA with all CRUD functionality connected to an OData web API restful service using angularjs . 
Enjoy AngularJS.....

      by Carmel Schvartzman


<<<<  PREVIOUS LESSON                        NEXT LESSON >>>>



כתב: כרמל שוורצמן