Complete Guide to CRUD operation using $http In Angularjs

In application development, Create, Read, Update, and Delete (CRUD) are the four basic functions of persistent storage, such as databases. CRUD refers to the commonly used functions in the relational database. The following table shows you how CRUD maps to the standard SQL and HTTP:

Operation SQL HTTP
Create Insert PUT/POST
Read Select GET
Update Update PUT/PATCH
Delete Delete Delete

In the following example, we will use $http of the angularjs framework to consume the ASP.NET Web API. In order to call the ASP.NET Web API, we first create a controller in a web API named CustomerController, which has the following action methods:

public class CustomerController : ApiController
    {
        NorthwindEntities _db = new NorthwindEntities();

        
        [HttpGet]
        public IHttpActionResult Customer()
        {
            _db.Configuration.ProxyCreationEnabled = false;

            var customer = _db.Customers;

            if (customer == null)
            {
                return NotFound();
            }
            return Ok(customer);
        }

        
        [HttpGet]
        public IHttpActionResult Customer(string customerID)
        {
            _db.Configuration.ProxyCreationEnabled = false;

            var customer = _db.Customers.FirstOrDefault(c => c.CustomerID == customerID);

            if (customer == null)
            {
                return NotFound();
            }
            return Ok(customer);
        }

        
        [HttpPut]
        public void Customer(Customer data, string customerID)
        {

            if (data.CustomerID == customerID)
            {
                _db.Entry(data).State = EntityState.Modified;
                _db.SaveChanges();
            }

        }

        

        [HttpDelete]
        public void Customer(string customerID, string nothing = null)
        {
            Customer customer = _db.Customers.Find(customerID);

            if (customer != null)
            {
                _db.Customers.Remove(customer);
                _db.SaveChanges();
            }
        }

        
        [HttpPost]
        public void Customer(Customer customer)
        {
            _db.Customers.Add(customer);
            _db.SaveChanges();

        }

    }

 

In the preceding code, note that the action method is declared as public void Customer(string customerID, string nothing = null). The second parameter in the method is a dummy parameter and will never be used. The only reason to declare this parameter is to fulfill the requirement of the overloaded methods, as the definition of overloaded methods states that it is a method with the same name and type but different data type or different number of parameters. As you can see, we have already declared the Customer action method with the parameter CustomerID string. This method will get a specific customer.

The following code example shows how to consume the preceding ASP.NET Web API using angularjs $http:

<! -- *********** GET ALL CUSTOMER ************* -- >
    
    var Url = '/api/Customer/Customer'

    $http({

            method: 'GET',
            url:Url

         }).success(function (customerList) {

            $scope.AllCustomer = customerList;

         }).error(function () {


    });


    <! -- ************ GET CUSTOMER BY CUSTOMER ID -- >
    $scope.GetCustomerByCustomerID = function(customerID)
    {
       $http({

                method: 'GET',
                url: Url,
                params: { customerID: customerID }

              }).success(function (customerList) {

                $scope.CustomerByID = customerList;
                $('#customerByIDModal ').modal('show');

             }).error(function () {


           });
    }

 

Using $http with the angularjs factory

All applications are composed of objects that work together to complete a task. These objects have to be instantiated and strengthened together for applications to work. In the angularjs framework, these objects are instantiated and bound together automatically with the injector service. However, the angularjs framework also offers factory, service, and provider “recipes” to produce and register our own objects. In angularjs, factory is the most popular recipe to create an object and configure a service. The advantage of creating objects in angularjs is the same as in object-oriented programming; we can use this object whenever we need it instead of creating it repeatedly.

In the following code example, we create an object (factory), which contains properties and then returns the same object. When we need to use this object (factory), we need to pass this object (factory) name into your controller. The properties of the object will then be available in the controller, as shown:

app.factory('myOperations', function ($http) {

    return {

        Create: function (Url, data) {

            return $http({
                method: 'POST',
                url: Url,
                data: data

            });

        },
        ReadList: function (Url) {

            //return $http.get(url);


            return $http({

                method: 'GET',
                url: Url

            })

        },
        Read: function (Url, parameters) {

            return $http({

                method: 'GET',
                url: Url,
                params: parameters

            })

        },

        Update: function (Url, parameters, data) {

            //return $http.put(url + customer.Id, data);

            return $http({

                method: 'PUT',
                url: Url,
                params: parameters,
                data: data

            })


        },

        Delete: function (id) {

            return $http.delete(url + id);

        }

 

In this example, we create a factory named myOperation, which contains the Create, ReadList, Read, Update, and Delete methods. The Create method of the myOperation factory requires two parameters: url to the web API and data in order to implement the HTTP post and create a new record in the database. Similarly, the ReadList method will return an array of the data retrieved from the database using HTTP GET. This method needs only one parameter, which is the url to the web API and so on.

This code shows the implementation of a factory in an angularjs controller:

app.controller('ctrlCustomer', function ($scope, $http, myOperations) {

    <!-- USING ANGULAR JS FACTORY -- >
    var Url = '/api/Customer/Customer';

    <! -- GET ALL CUSTOMER -- >
    myOperations.ReadList(Url).success(function (data) {

        $scope.Customers = data;

    }).error(function () {

    });
    <!--GET SPECIFIC CUSTOMER -- >
    $scope.GetCustomerByCustomerID = function (customerID, model) {

        myOperations.Read(Url, { customerID: customerID }).success(function (data) {

            $scope.Customer = data;
            $('#' + model).modal('show');

        }).error(function () {
            //ERROR GOES HERE
        });

    }

    <! -- UPDATE CUSTOMER-- >
    $scope.UpdateCustomer = function (CustomerID, Customer) {

     myOperations.Update(Url, { customerID: CustomerID },    
                         Customer).success(function (data) {

            $scope.Customer = data;

            <! -- GET UPDATED CUSTOMER LIST -- >
            myOperations.ReadList(Url).success(function (data) {

                $scope.Customers = data;

            }).error(function () {

            });



        }).error(function () {


        });


    }
});

In this example, we create the ctrlCustomer controller and inject our myOperation factory into the controller. We used the factory name in order to call the factory method in the controller. For example, myOperations.ReadList(Url).

Deven Rathore

Deven is an Entrepreneur, and Full-stack developer, Constantly learning and experiencing new things. He currently runs CodeSource.io and Dunebook.com.

Published by
Deven Rathore
Tags: angularjs

Recent Posts

Are There any Similarities Between Web Design and Art?

You may be surprised at how many of the same skills are involved!  Let’s get…

1 day ago

Tips on Increasing your organic traffic on WordPress

Introduction  As more and more people are using online services nowadays, most of the business…

2 days ago

Five Reasons You Should Start a Social Media Campaign

Small businesses need all the advertisements they can get. Traditional avenues for advertising, such as…

3 days ago

Top 10 SEO Writing Tips for Beginners 2021

Search Engine Optimization. It’s complicated, to say the least. Search engines, like Google, are constantly…

2 weeks ago

Should you become a freelancer in 2021? Pros and Cons

Freelancing and working from home was long considered idyllic by many, but the global pandemic…

2 weeks ago

The Leading Renewable Energy Trends in 2021

The past year saw slowdowns in the ongoing shift toward renewable energy in many countries…

2 weeks ago