Users Online

· Guests Online: 33

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

#0016 AngularJS AJAX Call using $resource, $http [Example]

AJAX is the short form of Asynchronous JavaScript and XML. AJAX was primarily designed for updating parts of a web page, without reloading the whole page.

The reason for designing this technology was to reduce the number of round trips which were made between the client and the server and the number of entire page refresh which used to take place whenever a user required certain information.

AJAX allowed web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This meant that it was possible to update parts of a web page, without reloading the whole page.

Many modern-day web applications actually follow this technique for refreshing the page or getting data from the server.

In this tutorial, you will learn-

High-level interactions with servers using $resource

Angular provides two different APIs to handle Ajax requests. They are

  • $resource
  • $http

We will look at the "$resource" property in Angular, which is used to interact with servers at a high level.

When we talk about interacting at a higher level, it means that we will only be bothered about what the server has to offer regarding functionality and not about what exactly the server does in detail with regards to this functionality.

For example, if the server was hosting an application which maintains the employee information of a certain company, the server might expose functionality to clients such as GetEmployeeDetails, SetEmployeeDetails, etc.

So at a high level, we know what these two functions can do, and we can invoke them using the $resource property. But then we don't know exactly the details of the "GetEmployeeDetails" and the "SetEmployeeDetails functions", and how it is implemented.

The above explanation explains what is known as a REST-based architecture.

  • REST is known as Representational State Transfer, which is an architecture followed in many modern web-based systems.
  • It means that you can use the normal HTTP verbs of GET, POST, PUT and DELETE to work with a web-based application.

So let's assume, we have a web application that maintains a list of Events.

If we wanted to get to the list of all of the events,

  • The web application can expose a URL such as http://example/events and
  • We can use the "GET" verb to get the entire list of events if the application is following a REST based architecture.

So for example, if there was an Event with an ID of 1, then we can get the details of this event via the URL. http://example/events/1

What is the $resource object

The $resource object in Angular helps in working with servers that serve applications on a REST based architecture.

The basic syntax of the @resource statement along with the various functions are given below

Syntax of @resource statement

var resource Object = $resource(url);  

Once you have the resourceObject at hand, you can use the below functions to make the required REST calls.

1. get([params], [success], [error]) – This can be used to make the standard GET call.

2. save([params], postData, [success], [error]) - This can be used to make the standard POST call.

3. query([params], [success], [error]) - This can be used to make the standard GET call, but an array is returned as part of the response.

4. remove([params], postData, [success], [error]) - This can be used to make the standard DELETE call.

In all of the functions given below the 'params' parameter can be used to provide the required parameters, which need to be passed in the URL.

For example,

  • Suppose you pass a value of Topic: 'Angular' as a 'param' in the get function as
  • get('http://example/events' ,'{ Topic: 'Angular' }')
  • The URL http://example/events?Topic=Angular gets invoked as part of the get function.

How to use $resource property

In order to use the $resource property, the following steps need to be followed:

Step 1) The file "angular-resource.js" needs to be downloaded from the Angular.JS site and has to place in the application.

Step 2) The application module should declare a dependency on the "ngResource" module in order to use the $resource.

In the following example, we are calling the "ngResource" module from our 'DemoApp' application.

angular.module(DemoApp,['ngResource']); //DemoApp is our main module

Step 3) Calling the $resource() function with your REST endpoint, as shown in the following example.

If you do this, then the $resource object will have the ability to invoke the necessary functionality exposed by the REST endpoints.

The following example calls the endpoint URL: http://example/events/1

angular.module('DemoApp.services').factory('Entry', function($resource) 
{
     return $resource('/example/Event/:1); // Note the full endpoint address
});

In the example above the following things are being done

  1. When defining the Angular application, a service is being created by using the statement 'DemoApp.services' where DemoApp is the name given to our Angular application.

  2. The .factory method is used to create the details of this new service.

  3. 'Entry' is the name we are giving to our service which can be any name you want to provide.

  4. In this service, we are creating a function which is going to call the $resource API

  5. $resource('/example/Event/:1).

    The $resource function is a service which is used to call a REST endpoint. The REST endpoint is normally a URL. In the above function, we are using the URL (/example /Event/:1) as our REST endpoint. Our REST endpoint(/example /Event/:1) denotes that there is an Event application sitting on our main site "example". This Event application is developed by using a REST-based architecture.

  6. The result of the function call is a resource class object. The resource object will now have the functions ( get() , query() , save() , remove(), delete() ) which can be invoked.

Step 4) We can now use the methods which were returned in the above step( which are the get() , query() , save() , remove(), delete() ) in our controller.

In the below code snippet, we are using the get() function as an example

Let's look at the code which can make use of the get() function.

angular.module('DemoApp.controllers',[]);
angular.module('DemoApp.controllers').controller('DemoController',function($scope, MyFunction) {
  var obj = MyFunction.get({ 1: $scope.id }, function() {
    console.log(obj);
  }); 

In the above step,

  • The get() function in the above snippet issues a GET request to / example /Event/:1.
  • The parameter:1 in the URL is replaced with $scope.id.
  • The function get() will return an empty object which is populated automatically when the actual data comes from the server.
  • The second argument to get() is a callback which is executed when the data arrives from the server. The possible output of the entire code would be a JSON object which would return the list of Events exposed from the "example" website.

    An example of what can be returned is shown below

    {
    { 'EventName' : 'Angular , 'EventDescription' : 'Angular Basics'},
    { 'EventName' : 'Node , 'EventDescription' : 'Node Basics'},
    { 'EventName' : 'Programming in C++ , 'EventDescription' : 'C++ Basics'}
    
    }

Low-level server interactions with $http

The $http is another Angular JS service which is used to read data from remote servers. The most popular form of data which is read from servers is data in the JSON format.

Let's assume, that we have a PHP page ( http://example/angular/getTopics.PHP ) that returns the following JSON data

"Topics": [
  {
    "Name" : "Controllers",
    "Description" : "Controllers in action"
  },
  {
    "Name" : "Models",
    "Description" : "Binding data using Models"
  },
  {
    "Name" : "Directives",
    "Description" : "Using directives in Angular"
  }
]

Let's look at the AngularJS code using $http, which can be used to get the above data from the server

<script>
var app = angular.module('myApp', []);
app.controller('AngularCtrl', function($scope, $http) {
    $http.get("http://example/angular/getTopics.PHP")
    .then(function(response) 
{
$scope.names = response.data.records;});
});
</script>

In the above example

  1. We are adding the $http service to our Controller function so that we can use the "get" function of the $http service.
  2. We are now using the get function from the HTTP service to get the JSON objects from the URL http://example /angular/getTopics.PHP
  3. Based on the 'response' object, we are creating a callback function which will return the data records and subsequently we are storing them in the $scope object.
  4. We can then use the $scope.names variable from the controller and use it in our view to display the JSON objects accordingly.

Fetching data from a server running SQL and MySQL

Angular can also be used to fetch data from a server running MySQL or SQL.

The idea is that if you have a PHP page connecting to a MySQL database or an Asp.Net page connecting to an MS SQL server database, then you need to ensure both the PHP and the ASP.Net page renders the data in JSON format.

Let's assume, we have a PHP site (http://example /angular/getTopics.PHP) serving data from either a MySQL or SQL database.

Step 1) The first step is to ensure that the PHP page takes the data from a MySQL database and serves the data in JSON format.

Step 2) Write the similar code shown above to use the $http service to get the JSON data.

Let's look at the AngularJS code using $http which can be used to get the above data from the server

<script>
var app = angular.module('myApp', []);
app.controller('AngularCtrl', function($scope, $http) {
    $http.get("http://example /angular/getTopics.PHP")
    .then(function(response) 
{
	$scope.topics = response.data.records;});
});
</script>

Step 3) Render the data in your view using the ng-repeat directive.

Below we are using the ng-repeat directive to go through each of the key-value pairs in the JSON objects returned by the "get" method of the $http service.

For each JSON object, we are displaying the key which is "Name" and the value is "Description".

<div ng-app="myApp" ng-controller="AngularCtrl"> 
<table>
  <tr ng-repeat="x in topics">
    <td>{{ x.Name }}</td>
    <td>{{ x.Description }}</td>
  </tr>
</table>
</div>

Summary:

  • We have had a look at what a RESTFUL architecture is, which is nothing but a functionality exposed by web applications based on the normal HTTP verbs of GET, POST, PUT and DELETE.
  • The $resource object is used with Angular to interact with the RESTFUL web applications at a high level which means that we only invoke the functionality exposed by the web application but don't bother of how the functionality is implemented.
  • We also looked at the $http service which can be used to get data from a web application. This is possible because the $http service can work with web applications at a more detailed level.
  • Because of the power of the $http service, this can be used to get data from a MySQL or MS SQL Server via a PHP application. The data can then be rendered in a table using the ng-repeat directive.

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.77 seconds
10,799,123 unique visits