Built-in and Custom Services

Slides:



Advertisements
Similar presentations
AngularJS Routing Routes, Route Parameters, Templates, Location, Navigation SoftUni Team Technical Trainers Software University
Advertisements

AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Templating, Routing, lodash Extending functionality using Collections SoftUni Team Technical Trainers Software University
Controllers and Markup Controllers, $scope, Markup, Directives, Expressions, Binding, Filters, Validation SoftUni Team Technical Trainers Software University.
AMD and RequireJS Splitting JavaScript Code into Dependent Modules Software University Technical Trainers SoftUni Team.
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
Promises and Asynchronous Programming Callback-oriented asynchrony, CommonJS Promise/A, Promises in Q, Promises in jQuery SoftUni Team Technical Trainers.
Web Storage and Cookies Cookies, Local and Session Storage SoftUni Team Technical Trainers Software University
AngularJS Best Practices High Quality SPA Applications SoftUni Team Technical Trainers Software University
AngularJS Best Practices High Quality SPA Applications SoftUni Team Technical Trainers Software University
Version Control Systems
Auto Mapping Objects SoftUni Team Database Applications
Introduction to Entity framework
Abstract Classes, Abstract Methods, Override Methods
C# Basic Syntax, Visual Studio, Console Input / Output
Interface Segregation / Dependency Inversion
Services & Dependency Injection
C# MVC Frameworks – ASP.NET
Web API - Introduction AJAX, Spring Data REST SoftUni Team Web API
Introduction to MVC SoftUni Team Introduction to MVC
Deploying Web Application
Reflection SoftUni Team Technical Trainers Java OOP Advanced
Introduction to Entity Framework
Application Architecture, Redux
ASP.NET Integration Testing
ASP.NET Unit Testing Unit Testing Web API SoftUni Team ASP.NET
Classes, Properties, Constructors, Objects, Namespaces
Mocking tools for easier unit testing
Parsing JSON JSON.NET, LINQ-to-JSON
State Management Cookies, Sessions SoftUni Team State Management
EF Code First (Advanced)
PHP MVC Frameworks MVC Fundamentals SoftUni Team Technical Trainers
Spring Filters Spring Interceptors SoftUni Team Spring Interceptors
EF Relations Object Composition
Entity Framework: Code First
MVC Architecture. Routing
Install and configure theme
Debugging and Troubleshooting Code
Entity Framework: Relations
Caching Data in ASP.NET MVC
The Right Way Control Flow
MVC Architecture, Symfony Framework for PHP Web Apps
Transactions in Entity Framework
AJAX and jQuery AJAX AJAX Concepts, XMLHttpRequest, jQuery AJAX: $.ajax(), $.get(), $.post() jQuery AJAX XMLHttpRequest SoftUni Team Technical Trainers.
ASP.NET MVC Introduction
Best Practices and Architecture
Best practices and architecture
Multidimensional Arrays, Sets, Dictionaries
Extending functionality using Collections
ASP.NET REST Services SoftUni Team ASP.NET REST Services
ASP.NET Filters SoftUni Team ASP.NET MVC Introduction
Making big SPA applications
Manual Mapping and AutoMapper Library
Functional Programming
ASP.NET Razor Engine SoftUni Team ASP.NET MVC Introduction
Introduction to TypeScript & Angular
CSS Transitions and Animations
Train the Trainers Course
Software Quality Assurance
Directives & Forms Capturing User Input SoftUni Team
Version Control Systems
JavaScript Frameworks & AngularJS
Extending the Functionality of Collections
Polymorphism, Interfaces, Abstract Classes
Lean .NET stack for building modern web apps
JavaScript: ExpressJS Overview
CSS Transitions and Animations
Presentation transcript:

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

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 – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

What is AngularJS Service? Reusable Components Holding App Logic

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, …

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

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

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

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

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

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

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.

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

$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); });

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

$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; }

$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); });

Built-In Angular Services Live Demo

Making AJAX calls $http and $resource

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"

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

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

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

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'); }]);

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; }]);

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

Making AJAX Calls Live Demo

Service, Factory, Provider What are the differences?

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

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(); });

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; });

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

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

Creating Custom Services Defining Reusable Services in Angular

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

Creating Custom Services Live Demo

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

AngularJS Services https://softuni.bg/courses/spa-applications-angularjs © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

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 – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

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