Tải bản đầy đủ (.pdf) (29 trang)

Angular JS session 6

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.28 MB, 29 trang )

Fo
rA
pt
ec
h
C
en
tre

U
se

O

nl
y


nl
y

Session Objectives

O

Explain the basic concepts of Representational State Transfer (REST) Application Programming Interface (API)

Explain client-server communication
List the steps to access server using various server resources

U


se

Describe the RESTful services in AngularJS

Fo
rA
pt
ec
h

C
en
tre

Explain error handling in AngularJS client-server communication

Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

2


Introduction to REST API

O

nl
y


Is a stateless architecture for networked applications and a lightweight alternative to Web
services.

U
se

Implements a cacheable client-server protocol, Hypertext Transfer Protocol (HTTP), for
communication through CRUD operations namely,

C
en
tre

Create (C)
Read (R)
Update (U)
Delete (D)

Simplifies network communication by avoiding complex means, including:
Simple Object Access Protocol (SOAP)
Remote Procedure Call (RPC)
Common Object Request Broker Architecture (CORBA)

Fo
rA
pt
ec
h


Is optimized for the World Wide Web, making it more popular than HTTP.

Is not a standard due to no World Wide Web Consortium (W3C) recommendation.

Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

3


REST Principles

O

nl
y

The REST architecture features a distinct set of constraints, also known as principles or
characteristics. There are six constraints, which are:
• Works on the principle of separation of concerns for making each component
independent.

Statelessness

• Ensures that no client information remains on the server after communication.

• Facilitates caching a server response on the client for using it later while
responding to a similar request in future.


• Simplifies interaction with different services and components and ensures
changes happen without affecting the whole interface or interaction.

Fo
rA
pt
ec
h

Uniform Interface

C
en
tre

Cacheability

U
se

Client-server Communication

Layered System

Code on Demand

• Allows having an intermediary between the client-server communication
without letting the client to know about it.


• Allows extending the client’s functionality on a temporary basis.

Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

4


SOAP

Fo
rA
pt
ec
h

REST

C
en
tre

U
se

O

nl

y

REST versus SOAP 1-2

Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

5


REST versus SOAP 2-2
SOAP

O

Point of
Distinction

nl
y

REST and SOAP have several differences.

REST

Is tightly coupled to the server, just as a custom
desktop application.


Is loosely coupled, just as a browser.

Orientation

Is object oriented.

Is resource oriented.

C
en
tre

Is heavy due to additional XML.

Size

U
se

Degree of Coupling

Is stateful.

Standard

Is standard specific.

Speed

Is slower due to strict specifications and

requirements for more bandwidth and
resources.

Fo
rA
pt
ec
h

State

Protocol Dependency

Communication
Implementation
Client

Is lightweight.
Is stateless.
Is not standard specific.

Is faster, as there are no strict
specifications and that it consumes less
resources and bandwidth.

Is independent of transport protocol in use. It
can use any transport protocol.

Is dependent on HTTP, although is not
coupled to it.


Uses only eXtensible Markup Language (XML).

Uses self-descriptive messages that control
interaction and are represented via media
types such as XML, plain text, and
JavaScript Object Notation (JSON).

Is not so easy.

Is easy.

Needs full knowledge on what it will be using,
prior to the interaction.

Has no knowledge of the API, except for
the entry point and media type (data
format).

Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

6


RESTful Web Services

nl

y

A RESTful Web service:

O

Uses HTTP methods.

Fo
rA
pt
ec
h

C
en
tre

U
se

Defines a URI that provides HTTP methods and a format for holding a resource.

Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

7



Resources in RESTful Web Services 1-2

nl
y

A resource:

Is of a particular type and holds data.

Has a state.

C
en
tre

Possesses a set of HTTP operation methods.

U
se

O

Is any content in a Web service with a unique URI, such as document, image, and collection of
users.

Is analogous to an object but has only a few HTTP methods unlike the latter.

Fo
rA

pt
ec
h

Is accessible by a REST client.

Is representable in a variety of media types such as XML and JSON.

Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

8


nl
y

Resources in RESTful Web Services 2-2

Fo
rA
pt
ec
h

C
en
tre


U
se

O

A collection is an unordered group of resources and is a resource in itself. All
resources inside are of a single type. It can be present globally.

Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

9


nl
y

HTTP Messages 1-3

Fo
rA
pt
ec
h

C
en

tre

U
se

O

A RESTful Web service uses HTTP for exchanging data between a client and a
server.

Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

10


HTTP Messages 2-3

U
se

O

Verb: Indicates an HTTP method.

nl
y


An HTTP Request consists of five parts, which are:

URI: Represents the identifier for recognizing the desired resource on the target
server.

C
en
tre

HTTP Version: Signifies the HTTP version, such as HTTP v1.1.
Request Header: Contains key-value pairs to show message’s metadata. For instance,
it includes the cache settings, type of browser, and message format.

Fo
rA
pt
ec
h

Request Body: Holds the message in the desired format.

Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

11


HTTP Messages 3-3


O

nl
y

An HTTP Response consists of four parts, which are:

U
se

HTTP Version: Signifies the HTTP version, such as HTTP v1.1.

C
en
tre

Response Code: Is in the form of three digits denoting the status for the resource
requested. For instance, code 404 means resource is not found on the server.
Request Header: Contains key-value pairs to show message’s metadata. For instance,
it includes the length of content, type of server, response date, and type of content.

Fo
rA
pt
ec
h

Request Body: Holds the message in the desired format.


Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

12


Response Codes
Message

Description

nl
y

HTTP Response
Code
OK

Indicates success.

201

Created

Indicates that the desired resource is successfully created via PUT or
POST request and returns a link to it through the location header.

204


No Content

Shows up when the response body is blank. For example, the code is
displayed when a DELETE request is successfully processed.

304

Not Modified

400

Bad Request

401

Unauthorized

404
409
500

U
se

C
en
tre

Is used for decreasing bandwidth usage if there are conditional GET

requests.
Indicates that an invalid input is given in the request.

Indicates that the client is using an unacceptable or wrong token of
authentication.

Fo
rA
pt
ec
h

403

O

200

Forbidden

Indicates that the client has no access to the requested method.

Not Found

Indicates that the method is unavailable.

Conflict

Indicates a conflict that is triggered while running the requested
method.


Internal Server Error

Indicates that the server has raised an exception while executing the
requested method.

Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

13


nl
y

RESTful Services in AngularJS

U
se

O

In AngularJS, three options exist for accessing services from a RESTful API:

Fo
rA
pt
ec

h

C
en
tre

Options for Accessing RESTful
Services

$http

Dynamic and Responsive Web Development Using
AngularJS

$resource

Restangular

© APTECH LIMITED

14


nl
y

$http Service in AngularJS

O


The $http service:

U
se

Sends an Asynchronous JavaScript and XML (AJAX) request to a
remote Web service on a server.

C
en
tre

Executes the request without waiting for the server’s reply.

Fo
rA
pt
ec
h

Fetches data from the Web service in the JSON format.

Implements HTTP methods.

Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

15



Syntax of $http

O

nl
y

The service is a function with a single parameter, which is the request configuration
object.
Syntax:

Fo
rA
pt
ec
h

where,

C
en
tre

U
se

$http({ method: 'GET', url: '/user1' })
success(function (data, status, headers, config) {

// ...
})
error(function (data, status, headers, config) {
// ...
});

success and error: Are callback methods of the promise object that get()returns.
data: Is the server’s response as a string or an object.
status: Is the HTTP status code.
headers: Refers to a function that fetches header information.
config: Refers to the configuration object that created the request.

Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

16


Promise Object

nl
y

The promise object:

Indicates what to do when an action succeeds or fails.

U

se

O

Denotes the final outcome of an action.

Refers to two callback methods to handle the server’s response.

C
en
tre

Triggers success() when the response is successfully available.

Triggers error() when the response contains an error status code and returns a single object with properties
such as data and statusText to convey the reasons of failure.

Fo
rA
pt
ec
h

Following example shows how to make a request asynchronously:
$var promise = $http.get("/api/emp/lastname");
promise.success(function(name) {
console.log("Request succeeded. " + "Name is: " + name);
});
promise.error(function(response, status) {
console.log("Request failed: " + response + " with status code " + status);

});

Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

17


Using $http in AngularJS

Output:

Fo
rA
pt
ec
h

C
en
tre

U
se

O

nl

y

Following example shows how the then keyword takes the callback functions of promise
object as parameters:

Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

18


$resource Service in AngularJS

nl
y

The $resource service:

Implements CRUD methods.
Is built on the top of $http.

C
en
tre

Facilitates communication with the backend.

U

se

O

Fetches data to manipulate and return it.

Following example shows how to use the $resource service for implementing the GET method in
AngularJS:

Fo
rA
pt
ec
h

var Tasks = $resource('/task/:taskId', { taskId: '@id' });
var task = Tasks.get({ taskId: 1023 }, function () {
task.abc = true;
task.$save();
});

Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

19


Restangular Tool


O

nl
y

Restangular tool:

U
se

Is a third-party, open-source framework.

C
en
tre

Minimizes coding for HTTP communication through CRUD operations.

Fo
rA
pt
ec
h

Is ideal for Web applications using data from a RESTful API.

Supports all HTTP methods, facilitates creating custom methods, and removes the need to mention the
URL; unlike $resource.


Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

20


Server Communication

U
se

O

nl
y

For communicating with a Web server, AngularJS:

C
en
tre

Offers low-level mechanism and built-in wrappers for interacting with RESTful services.

Fo
rA
pt
ec

h

Supports AJAX due to which there is no need to refresh the whole page for updating a
part of it.

Fetches layout and data separately.

Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

21


Accessing Server Resources with $http 1-2

nl
y

For accessing server resources, the $http service:

O

Implements the standardized way of handling asynchronous calls through promise.

U
se

Triggers generic AJAX calls that can interact with the RESTful or Non-RESTful API on the server.

Offers two ways, JSONP or XMLHttpRequest object of the browser.

C
en
tre

Provides the following functionalities:
GET
POST
HEAD
PUT
DELETE
JSONP

Fo
rA
pt
ec
h

Following example shows how $http retrieves a server resource, assessment:

Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

22



O

Following are the four steps for accessing server resources via $http:

nl
y

Accessing Server Resources with $http 2-2

U
se

1. Define a custom
service for injecting the
$http service directly
into it.

Fo
rA
pt
ec
h

C
en
tre

2. Use the $http
service with an
appropriate request

method.

Dynamic and Responsive Web Development Using
AngularJS

3. Pass the config object
as the parameter to return
a promise object.

4. Fetch the response
once the request has
been processed.

© APTECH LIMITED

23


Handling Errors in Client-Server Communication 1-3

U
se

O

nl
y

Error handling is essential to find the legible reasons of a failure that occurs. Following are the ways
in which AngularJS facilitates exception handling:


C
en
tre

Exception Handling
Ways

Fo
rA
pt
ec
h

JavaScript Blocks

Try

Catch

Dynamic and Responsive Web Development Using
AngularJS

Finally

$exceptionHandler

Logs error into
$log.error


© APTECH LIMITED

24


Handling Errors in Client-Server Communication 2-3
handle

an

uncaught

exception

nl
y

to

through

the

Fo
rA
pt
ec
h

C

en
tre

U
se

O

Following example shows how
$exceptionHandler service:

Dynamic and Responsive Web Development Using
AngularJS

© APTECH LIMITED

25


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×