Communicating with the server using RESTful services and $resource

Representational State Transfer (REST) is architecture of World Wide Web that consists of a set of architectural constraints, which can be applied to components, connectors, and data elements. In order to put emphasis on the role of components, interaction with other components, and clarification of data elements, the REST architecture ignores the details of implementation and protocol syntax.

REST was introduced by Roy Fielding in his PhD dissertation at the University of California, Irvine, in 2000. REST defines the desired web architecture to classify current problems, to associate different solutions, and to make sure that protocol additions would not disturb the core constraints that make the Web successful. REST has the following six constraints:

  • Uniform interface:

    This defines the interface between the clients and server. It streamlines and decouples the architecture so that each part can advance autonomously. The following are the four principles of a uniform interface:

    • Resource-based interface:

      Using Universal Resource Identifiers (URIs), distinct resources are identified.

    • Manipulation of resources through representation:

      When the client has a resource that includes any metadata, the client is able to update or delete the data on the server.

    • Self-descriptive message:

      Each message describes how to process the message on the server because it includes enough information.

    • Hypermedia as the engine of application state (HATEOAS):

      Responses are contained in the body element to provide retrieval of the object itself or other related objects.

  • Stateless:

    The server does not need to remember the session information or status of communication during multiple requests. The connection between the client (browser) and server will be lost when the transaction gets completed.

  • Cacheable:

    On the client side, we can cache the server response. Therefore, the server has to implicitly or explicitly define whether or not the response is cacheable.

  • Client-server:

    The client and server are separate. The client is the browser or machine that the user has access to while the server is a centralized resource where data and applications are stored.

  • Layered system:

    The client cannot figure out whether it is connected to the end server or an intermediary server.

  • Code on demand (optional):

    The server can provisionally extend the functionality of a client by shifting logic to the client.

The AngularJS $http service gives us a lot of control and provides us with a very low-level implementation that allows us to make an XHR request. Most of the time on the client side, we deal with objects and object models that are condensed with functions and properties. For example, a car object contains the properties Color, Model, and so on. In this scenario, it would be nice if on the client side we had an object that comprehends and represents the server model, so that we can just edit the properties of the server-side object from the client-side object and save the changes on the server. Therefore, the server gets the preserved state. We can achieve this using $resource of the AngularJS framework.

The AngularJS $resource permits us to outline the object model on the client side. We can use the AngularJS $resource if the server side acts in a RESTful manner. The AngularJS $resource allows us to query the server-side object as we need. For example, a GET request to the /Cars/getCarInfo/:Model=Toyota server will return a list of cars where the car's model is Toyota. $resource also keeps track of the changes that we made to the returned object from the server. $resource gives us the query, get, save, remove, and delete functions to work with an object.

In the AngularJS framework, ngResource is a separate optional model that needs to be injected in the application model in order to use it. We can inject ngResouce as shown in the following line of code:

var app = angular.model('myApp',['ngResource']);

$resource has the following syntax:

$resource(url, [paramDefaults], [actions], options);

In the preceding syntax:

  • url: This is a parameterized URL.
  • paramDefault: These are the URL default parameter's values. If any of the parameter values is a method, it will be overridden by actions. For example, '/Cars/getCarInfo/:Model=Toyota'.
  • action: This is the name of the function of $resource, such as query, get, save, and remove. The syntax of the $resource function is {action1: {method:?, params:?, isArray:?, headers:?...} in which:
    • method: This refers to the HTTP methods, such as GET, POST, PUT, DELETE, and so on.
    • params: This is an optional set of predefined parameters.
    • isArray: The return array for this action if it is true.
    • transformRequest: This transforms function or any array of such functions. The transform function takes the HTTP response body and headers and returns them transformed. It is usually used to override the default transformation.
    • transformResponse: It takes the HTTP response body and header and returns them transformed.
    • cache: $http will use the default cache if it is true.
    • timeout: This is the timeout in milliseconds.
    • withCredentials: To set the withCredentials flag on.
    • responseType: This is the request type.
    • intercepter: This function has two optional functions response and responseError.

The following code shows the use of $resource:

var car = $resource('/Cars/getCarsInfo/:Year')
<!- - Insert new record -- > 

var addNewCar = new car();

addNewCar.Model='Toyota Corola';

addNewCar.Year = '2014'

addNewCar.Color='Black'

addNewCar.$save();

<!- - update record -- > 

var updateCarInfo = car.get({Year:2014});

updateCarInfo.Color = 'White';

updateCarInfro.$save();

<!- - Get a list  records-- > 

car.query(function(list){
     
 <!- - To do something with list -- >

});

<!- - Delete a records -- > 

Car.$delete({Year:2014});

In the preceding code, we saw how to implement $resource and how to use its get, query, save, and delete functions. We will implement these functions with the real web API examples in Chapter 5, Creating Application Using AngularJS, Entity Framework, and ASP.NET Web API.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset