Presentation is loading. Please wait.

Presentation is loading. Please wait.

Built-in and Custom Services

Similar presentations


Presentation on theme: "Built-in and Custom Services"— Presentation transcript:

1 Built-in and Custom Services
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

2 Table of Contents What is a AngularJS Service?
Why Should You Use Services? Built-In Services Making AJAX Calls $http and $resource Build-in Services Interceptors Service, Factory, Provider Creating Custom Services © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

3 What is AngularJS Service?
Reusable Components Holding App Logic

4 What is AngularJS Service?
A worker object that performs some sort of logic Not necessarily over-the-wire Often stateless Lazily instantiated Singletons Built-in services always start with $ E.g. $http, $location, $log, $q, $animate, …

5 Why Use Services? Reusability Dependency Injection
Services encapsulate reusable business logic Dependency Injection Inject services into controllers / other services Single Responsibility Principle Better encapsulation Testable

6 Built-In Angular Services
$http, $resource, $location, $q, …

7 Built-In Angular Services
$http – communication with remote servers via HTTP $resource – RESTfull server-side data sources interaction $location – navigation between pages in the app $route / $routeParams – map URL to routes $q – promise library for asynchronous execution $exceptionHandler – handles uncaught exceptions $anchorScroll – scrolls to the related element

8 Built-In Angular Services (2)
$cacheFactory – cache functionality $compile – compiles an HTML string or DOM $parse – converts AngularJS expression into a function $locale – localization rules for various Angular components $timeout – timeout with compiling (like setTimeout) $filter – formatting data displayed to the user $cookieStore – cookies wrapper

9 Other Built-In Angular Services
$interpolate $log $rootScope $window $document $rootElement $httpBackend $controller

10 Angular’s answer to promises
Angular $q Angular’s answer to promises

11 Angular $q Build on top of Kris Kowal’s Q
$q is integrated with the $rootScope.Scope Scope model observation mechanism in angular, which means faster propagation of resolution or rejection into your models Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains all the important functionality needed for common async tasks.

12 Angular $q Types of Usage
ES6 (ES2015) promises implementation ES6 style promise is essentially just using $q as a constructor which takes a resolve and reject functions as arguments progress/notify callbacks are not currently supported Similar to Kris Kowal's Q or jQuery's Deferred implementations A new instance of deferred is constructed by calling $q.defer() The deferred object exposes the associated Promise instance, which can then be used for signaling the successful or unsuccessful completion, as well as the status of the task

13 $q ES6 Implementation – Example (1)
function asyncGreet(name, okToGreet) { return $q(function(resolve, reject) { setTimeout(function() { if (okToGreet) { resolve('Hello, ' + name + '!'); } else { reject('Greeting ' + name + ' is not allowed.'); } }, 1000); });

14 $q ES6 Implementation – Example (2)
var promise = asyncGreet(’Nakov'); promise.then(function(greeting) { alert('Success: ' + greeting); }, function(reason) { alert('Failed: ' + reason); });

15 $q Deferred Implementation – Example (1)
function asyncGreet(name, okToGreet) { var deferred = $q.defer(); setTimeout(function() { deferred.notify('About to greet ' + name + '.'); if (okToGreet) { deferred.resolve('Hello, ' + name + '!'); } else { deferred.reject('Greeting ' + name + ' is not allowed.'); }}, 1000); return deferred.promise; }

16 $q Deferred Implementation – Example (2)
var promise = asyncGreet(’Ivaka’, true); promise.then(function(greeting) { alert('Success: ' + greeting); }, function(reason) { alert('Failed: ' + reason); }, function(update) { alert('Got notification: ' + update); });

17 Built-In Angular Services
Live Demo

18 Making AJAX calls $http and $resource

19 Making AJAX Calls $http $resource
For general purpose AJAX. With $http you're going to be making GET, POST, DELETE type calls manually and processing the objects they return manually. Can be used in both RESTful and Non-RESTful scenarios. $resource Wraps $http for use in RESTful web API scenarios. Allows you to pass in a template string (a string that contains placeholders) along with the parameters values. Example: "/api/cars/:carId"

20 How to plug to the request and responses
Interceptors How to plug to the request and responses

21 Interceptors Intercept a request by implementing the request function
This method is called before $http sends the request to the backend, so you can modify it Intercept a response by implementing the response function This method is called right after $http receives the response from the backend, so you can modify it Intercept request or response error by implementing the requestError / responseError function Sometimes a request can’t be sent or it is rejected by an interceptor. Other times our backend call fails and this is where the request / response error interceptors help us to recover the failed AJAX

22 Interceptors – Creation Example (1)
module.factory('myInterceptor', ['$log', function($log) { $log.debug('$log is here to show you that this is a regular factory with injection'); var myInterceptor = { request: function(config) { // Asynchronous operation succeeded, modify config accordingly return config; }, requestError: function(config) { // Asynchronous operation failed, modify config accordingly

23 Interceptors – Creation Example (2)
response: function(res) { // Asynchronous operation succeeded, modify response accordingly return res; }, responseError: function(res) { // Asynchronous operation failed, modify response accordingly } }; return myInterceptor; }]); module.config(['$httpProvider', function($httpProvider) { $httpProvider.interceptors.push('myInterceptor'); }]);

24 Interceptors – Timestamp Marker Example (1)
module.factory('timestampMarker', [function() { var timestampMarker = { request: function(config) { config.requestTimestamp = new Date().getTime(); return config; }, response: function(response) { response.config.responseTimestamp = new Date().getTime(); return response; } }; return timestampMarker; }]);

25 Interceptors – Timestamp Marker Example (2)
module.config(['$httpProvider', function($httpProvider) { $httpProvider.interceptors.push('timestampMarker'); }]); $http.get(' { var time = response.config.responseTimestamp - response.config.requestTimestamp; console.log('The request took ' + (time / 1000) + ' seconds.'); });

26 Making AJAX Calls Live Demo

27 Service, Factory, Provider
What are the differences?

28 Services, Factories, Providers
Instantiated behind the scenes with the new keyword. You add properties to this and the service will return this. Factories You create an object, add properties to it, then return that same object. Providers Instantiated with new, then returns the $get method of the instance The only service you can pass into your .config() function

29 Services - Example app.service('service', function() { var name = '';
this.setName = function(newName) { name = newName; } this.getName = function() { return name; }); app.controller('ctrl', function($scope, service) { $scope.name = service.getName(); });

30 Factories - Example app.factory('factory', function() { var name = '';
// Return value **is** the object that will be injected return { name: name; } }) app.controller('ctrl', function($scope, factory) { $scope.name = factory.name; });

31 Providers – Example (1) app.provider('provider', function() {
var name = ''; this.setName = function(newName) { name = newName; } this.$get = function() { return { name: name })

32 Providers – Example (2) app.controller('ctrl', function($scope, provider) { $scope.name = provider.name; }); app.config(function(providerProvider) { providerProvider.setName('John'); });

33 Creating Custom Services
Defining Reusable Services in Angular

34 Creating Custom Angular Service
myApp.factory('data', function data() { return { getVideos: getAllVideos, addVideo: addVideo, } }); myApp.controller('VideosController', function VideosController($scope, data) { data.getVideos(); });

35 Creating Custom Services
Live Demo

36 SPA with AngularJS Summary
Which would be the best way to access a RESTFul web service? Using $resource service Which service would you use to localize date-time? $locale Can child scopes access items on the root scope? Yes, due to prototypal inheritance SPA with AngularJS

37 AngularJS Services © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

38 License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International" license Attribution: this work may contain portions from "SPA with AngularJS" course by Telerik Academy under CC-BY-NC-SA license © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

39 Free Trainings @ Software University
Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software Facebook facebook.com/SoftwareUniversity Software YouTube youtube.com/SoftwareUniversity Software University Forums – forum.softuni.bg © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.


Download ppt "Built-in and Custom Services"

Similar presentations


Ads by Google