1. Trang chủ
  2. » Mẫu Slide

Angular JS session 6

29 8 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 29
Dung lượng 1,28 MB

Nội dung

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 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 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 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 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 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 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 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 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 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 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 Define a custom service for injecting the $http service directly into it Fo rA pt ec h C en tre Use the $http service with an appropriate request method Dynamic and Responsive Web Development Using AngularJS Pass the config object as the parameter to return a promise object 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 Handling Errors in Client-Server Communication 3-3 Fo rA pt ec h C en tre U se O nl y Following is the output of code showing how to handle an uncaught exception through the $exceptionHandler service: Dynamic and Responsive Web Development Using AngularJS © APTECH LIMITED 26 Communication Using $resource 1-2 O nl y The main AngularJS script files does not include the $resource service Thus, it is essential to download its file and add it to the index.html file U se Following example shows how to include the $resource service in index.html: Following example shows how to so: C en tre Next, declare a dependency on $resource so that a controller can use it Finally, call the $resource() function with the targeted REST endpoint address Fo rA pt ec h angular.module('resourceApp.services').factory('Domain', function($resource) { return $resource('/api/domains/:empid'); }); The function returns $resource object, which communicates with a REST backend server By default, the $resource object possesses five methods, which are get(), save(), query(), delete(), and remove() Dynamic and Responsive Web Development Using AngularJS © APTECH LIMITED 27 Communication Using $resource 2-2 O nl y Following example shows usage of query(), get(), and save() methods: C en tre U se angular.module('resourceApp.controllers',[]); angular.module('resourceApp.controllers').controller('ResourceController',function($scope, Domain) { var domain = Domain.get({ empid: $scope.empid }, function() { console.log(domain); }); // get() returns a single domain var domains = Domain.query(function() { console.log(domains); }); //query() returns all the domains Fo rA pt ec h $scope.domain = new Domain();//instantiates the resource class $scope.domain.data = 'returned data'; Domain.save($scope.domain, function() { //code to something }); }); Dynamic and Responsive Web Development Using AngularJS © APTECH LIMITED 28 Summary O nl y REST is a stateless and lightweight architecture using HTTP for communication among Web applications U se RESTful applications work on six principles or constraints namely client-server communication, statelessness, cacheability, uniform interface, layered system, and code on demand C en tre The REST architecture implements CRUD operations A RESTful Web service manages its content as resources, which can be represented in a variety of formats or media types Fo rA pt ec h The $http service communicates asynchronously with a Web service and returns a Promise object $resource is a better option than $http for interacting with a RESTful Web service as well as a backend The $exceptionHandler service catches an uncaught exception, but cannot catch a syntax error Dynamic and Responsive Web Development Using AngularJS © APTECH LIMITED 29 ... 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... 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... 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

Ngày đăng: 30/12/2022, 19:30

w