SlideShare a Scribd company logo
1 of 56
Download to read offline
service-side development
quick introduction
Nir Kaufman 
Head of AngularJS development department @ 
Nir@500tech.com
We will cover: 
services - definition 
dependency injection 
services types 
common patterns
all examples and reference code 
are written in ES6
Services defined
the term ‘services’ refers to 
injectable objects 
whose API is defined 
by the developer (not the framework)
services contain 
reusable business logic 
independent of views
each service starts as a 
plain javaScript! 
object, function or primitive
we use one of the module 
methods to register! 
our code as a service
now we can inject it 
into other angular components like 
controllers, directives & services
Dependency Injection
let’s take a high level overview 
of dependency injection 
in angular!
the key players are the 
provide & injector! 
services
we register our code on the 
injector with the provide service 
https://docs.angularjs.org/api/auto/service/$provide
we need to provide a 
key as the first argument
the injector keeps our code in an 
internal object called 
providerCache 
angular source code, line 3926
we use the injector retrieve object 
instances 
https://docs.angularjs.org/api/auto/service/$injector
the first time we inject a service, the 
injector evaluates the code and 
stores the result in an 
instanceCach object
the next time that we inject the 
same service, the injector will first 
look in the instanceCache 
angular source code, line 3940
that’s why our services are 
singletons
we can’t use a service in the module 
config phase because the instanceCache 
is empty 
until the service is injected for the first 
time
registering services
We don’t need to use the provider 
directly. The module exposes 
the necessary methods. 
https://docs.angularjs.org/api/ng/type/angular.Module
the module exposes 5 methods 
used to instruct the injector how to 
evaluate our code
.provider! 
an object with a $get method.
module.provider 
Construction function for creating new instance of the service. 
class Logger { 
! 
constructor() { 
! 
let logToConsole = false; 
! 
this.enableConsole = function (flag) { 
logToConsole = flag; 
}; 
! 
this.$get = function() { 
return { 
debug: function (msg) { 
if (logToConsole) { 
console.log(msg) 
} 
} 
} 
} 
} 
}
module.provider 
use it if you need to config your service before it’s instantiated 
class Logger { 
! 
constructor() { 
! 
let logToConsole = false; 
! 
this.enableConsole = function (flag) { 
logToConsole = flag; 
}; 
! 
this.$get = function() { 
return { 
debug: function (msg) { 
if (logToConsole) { 
console.log(msg) 
} 
} 
} 
} 
} 
} 
angular.module('app', []) 
! 
.provider(‘logger’, Logger) 
.config(function(loggerProvider){ 
loggerProvider.enableConsole(false); 
}) 
! 
.run(function(logger){ 
logger.debug(‘log message'); 
}); 
we need to call our service 
with a ‘Provider’ suffix when 
injecting into config function.
.service! 
plain javaScript Object
module.service 
a constructor function that will be instantiated. 
class Logger { 
! 
constructor() { 
this.enableConsole = true; 
} 
! 
debug(msg) { 
if (this.enableConsole) { 
console.log(msg) 
} 
} 
}
module.service 
use if your object does not need to be configured. 
class Logger { 
! 
constructor() { 
this.enableConsole = true; 
} 
! 
debug(msg) { 
if (this.enableConsole) { 
console.log(msg) 
} 
} 
} 
angular.module('app', []) 
! 
.service(‘logger’, Logger) 
! 
.run(function(logger){ 
logger.debug(‘log message'); 
});
.factory! 
just a plain function
module.factory 
Function for creating new instance of an Object. 
function logger() { 
! 
return { 
! 
debug: function (msg) { 
console.log(msg); 
} 
} 
} 
! 
! 
! 
function logger() { 
! 
return function (flag) { 
return function (msg) { 
if (flag) console.log(msg); 
} 
} 
} 
! 
!
module.factory 
if you want to return something other than an Object instance 
function logger() { 
! 
return { 
debug: function (msg) { 
console.log(msg); 
} 
} 
} 
! 
! 
function logger() { 
! 
return function (flag) { 
return function (msg) { 
if (flag) console.log(msg); 
} 
} 
} 
! 
! 
angular.module('app', []) 
.factory(‘logger’, logger) 
.run(function(logger){ 
logger.debug(‘log message'); 
}); 
angular.module('app', []) 
! 
.factory(‘logger’, logger) 
.run(function(logger){ 
logger(true)(‘log message'); 
});
.value! 
a value of any type
module.value 
Service instance object. registered “as-is”. 
function randomise() { 
return Math.random() * 10; 
} 
! 
var id = 52334556; 
! 
var product = {id: 52345, inStock: true}; 
! 
! 
class User { 
! 
constructor(name) { 
this.firstName = name; 
} 
}
module.value 
use it when you need a simple object or primitive. 
function randomise() { 
return Math.random() * 10; 
} 
! 
! 
! 
! 
! 
! 
! 
! 
class User { 
! 
constructor(name) { 
this.firstName = name; 
} 
} 
angular.module('app', []) 
! 
.value(‘randomise’, randomise) 
! 
.run(function(randomise){ 
var num = randomise() 
}); 
angular.module('app', []) 
! 
.value(‘User’, User) 
! 
.run(function(user){ 
var joe = new User(‘joe’) 
});
.constant! 
a value of any type
module.constant 
Constant value. registered on the injector instanceCache. 
var SERVERS = { 
DEVELOPMENT : "http://localhost:8080/app", 
DEBUGGING : "http://localhost:5789", 
PRODUCTION : "http://application.com" 
}; 
angular.module('app', []) 
.constant('SERVERS', SERVERS) 
! 
.config(function (SERVERS) { 
console.log(SERVERS.PRODUCTION); 
}) 
! 
.run(function (SERVERS) { 
console.log(SERVERS.DEVELOPMENT); 
}); 
because constants are 
registered on the 
injector instanceCache, 
they can be injected 
into the config function.
service and factory are shorthands for providers 
class Logger { 
! 
constructor() { 
! 
let logToConsole = false; 
! 
this.enableConsole = function (flag) { 
logToConsole = flag; 
}; 
! 
this.$get = 
! 
function () { 
return { 
debug: function (msg) { 
if (logToConsole) { 
console.log(msg) 
} 
} 
} 
} 
} 
} 
Provider 
Factory 
Service
common patterns
Problem:! 
I want to decide which service to 
inject dynamically.
Solution:! 
use the $injector service to grab an 
instance of the service you need.
show me some code! 
class Logger { 
! 
constructor($injector) { 
this.injector = $injector; 
} 
! 
debug(msg, useLogService) { 
useLogService ? 
this.injector.get('$log').debug(msg) 
: console.log(msg); 
} 
} 
angular.module('app', []) 
! 
.service('logger', ['$injector', Logger]) 
! 
.run(function (logger) { 
logger.debug('something to debug', true) 
}); 
dynamic-inject.js
Problem:! 
I want to be able to extend an 
existing service.
Solution:! 
Services are plain javaScript 
objects. Prototypal inheritance 
works as usual.
show me some code! 
class ItemList { 
! 
constructor() { 
this.items = []; 
} 
! 
addItem(item) { 
this.items.push(item); 
} 
! 
removeItem(item){ 
this.items.splice(this.items.indexOf(item), 1); 
} 
} 
!! 
class TaskList extends ItemList { 
! 
constructor() { 
super() 
} 
! 
getItems () { 
return this.items; 
} 
} 
angular.module('app', []) 
! 
.service('taskList', TaskList) 
prototype-inheritance.js 
! 
.run(function (taskList) { 
taskList.addItem("some item to be added"); 
console.log(taskList.getItems()); 
});
Problem:! 
I want to be able to extend core 
angular or 3rd party services.
Solution:! 
use the $decorator method to 
extend or override services.
show me some code! 
function logDecorator($delegate) { 
! 
$delegate.debug = function (msg) { 
let time = new Date().getTime(); 
console.log(time + " : " + msg); 
}; 
! 
return $delegate 
} 
! 
export default logDecorator; 
decorator.js 
angular.module('app', []) 
! 
.config(['$provide', function ($provide) { 
$provide.decorator('$log', logDecorator) 
}]) 
! 
.run(['$log', function ($log){ 
$log.debug('logging with timestamp!'); 
}]);
Problem:! 
I want to register new services at 
runtime (lazy register)
Solution:! 
get a reference to the $provide 
service and use it outside the 
config block
show me some code! 
class Product { 
! 
constructor(type) { 
this.productType = type; 
} 
! 
getType () { 
return this.productType; 
} 
} 
! 
class ProductFactory { 
! 
constructor($provider) { 
! 
let provider = $provider; 
! 
this.$get = function () { 
return { 
registerProduct : function (type) { 
provider.value(type, new Product(type)); 
} 
} 
} 
} 
} product-factory.js
show me some code! 
angular.module('app', []) 
! 
.provider('productFactory', ['$provide',ProductFactory]) 
! 
.run(function($injector, productFactory) { 
! 
productFactory.registerProduct(‘chair'); 
! 
var theChair = $injector.get(‘chair'); 
! 
console.log(theChair.getType()); 
}); 
product-factory.js
grab the code 
https://github.com/nirkaufman/angularjs-services
Thank you.

More Related Content

What's hot

Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectJadson Santos
 
Angular Advanced Routing
Angular Advanced RoutingAngular Advanced Routing
Angular Advanced RoutingLaurent Duveau
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoKnoldus Inc.
 
Angular Pipes Workshop
Angular Pipes WorkshopAngular Pipes Workshop
Angular Pipes WorkshopNir Kaufman
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency InjectionNir Kaufman
 
Angular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariAngular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariSurekha Gadkari
 
Angular 16 – the rise of Signals
Angular 16 – the rise of SignalsAngular 16 – the rise of Signals
Angular 16 – the rise of SignalsCoding Academy
 
Angular directives and pipes
Angular directives and pipesAngular directives and pipes
Angular directives and pipesKnoldus Inc.
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions WebStackAcademy
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Knoldus Inc.
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation洪 鹏发
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptForziatech
 

What's hot (20)

Angular 8
Angular 8 Angular 8
Angular 8
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
 
Angularjs PPT
Angularjs PPTAngularjs PPT
Angularjs PPT
 
Angular Advanced Routing
Angular Advanced RoutingAngular Advanced Routing
Angular Advanced Routing
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Angular Pipes Workshop
Angular Pipes WorkshopAngular Pipes Workshop
Angular Pipes Workshop
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency Injection
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 
Angular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariAngular Introduction By Surekha Gadkari
Angular Introduction By Surekha Gadkari
 
Angular 16 – the rise of Signals
Angular 16 – the rise of SignalsAngular 16 – the rise of Signals
Angular 16 – the rise of Signals
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Angular 9
Angular 9 Angular 9
Angular 9
 
Angular directives and pipes
Angular directives and pipesAngular directives and pipes
Angular directives and pipes
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
Angular
AngularAngular
Angular
 
Angular 14.pptx
Angular 14.pptxAngular 14.pptx
Angular 14.pptx
 
Spring boot
Spring bootSpring boot
Spring boot
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
 

Viewers also liked

Webpack and angularjs
Webpack and angularjsWebpack and angularjs
Webpack and angularjsNir Kaufman
 
Data Structures in javaScript 2015
Data Structures in javaScript 2015Data Structures in javaScript 2015
Data Structures in javaScript 2015Nir Kaufman
 
redux and angular - up and running
redux and angular - up and runningredux and angular - up and running
redux and angular - up and runningNir Kaufman
 
Up & running with ECMAScript6
Up & running with ECMAScript6Up & running with ECMAScript6
Up & running with ECMAScript6Nir Kaufman
 
Angular js - 10 reasons to choose angularjs
Angular js - 10 reasons to choose angularjs Angular js - 10 reasons to choose angularjs
Angular js - 10 reasons to choose angularjs Nir Kaufman
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing optionsNir Kaufman
 
Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016Nir Kaufman
 
How Angular2 Can Improve Your AngularJS Apps Today!
How Angular2 Can Improve Your AngularJS Apps Today!How Angular2 Can Improve Your AngularJS Apps Today!
How Angular2 Can Improve Your AngularJS Apps Today!Nir Kaufman
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introductionNir Kaufman
 
Angular2 - getting-ready
Angular2 - getting-ready Angular2 - getting-ready
Angular2 - getting-ready Nir Kaufman
 
AngularJS performance & production tips
AngularJS performance & production tipsAngularJS performance & production tips
AngularJS performance & production tipsNir Kaufman
 
Angular2 workshop
Angular2 workshopAngular2 workshop
Angular2 workshopNir Kaufman
 
RESTful API 제대로 만들기
RESTful API 제대로 만들기RESTful API 제대로 만들기
RESTful API 제대로 만들기Juwon Kim
 
Angularjs - lazy loading techniques
Angularjs - lazy loading techniques Angularjs - lazy loading techniques
Angularjs - lazy loading techniques Nir Kaufman
 

Viewers also liked (18)

Webpack and angularjs
Webpack and angularjsWebpack and angularjs
Webpack and angularjs
 
Data Structures in javaScript 2015
Data Structures in javaScript 2015Data Structures in javaScript 2015
Data Structures in javaScript 2015
 
redux and angular - up and running
redux and angular - up and runningredux and angular - up and running
redux and angular - up and running
 
Up & running with ECMAScript6
Up & running with ECMAScript6Up & running with ECMAScript6
Up & running with ECMAScript6
 
Solid angular
Solid angularSolid angular
Solid angular
 
Angular js - 10 reasons to choose angularjs
Angular js - 10 reasons to choose angularjs Angular js - 10 reasons to choose angularjs
Angular js - 10 reasons to choose angularjs
 
Angular redux
Angular reduxAngular redux
Angular redux
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing options
 
Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016
 
How Angular2 Can Improve Your AngularJS Apps Today!
How Angular2 Can Improve Your AngularJS Apps Today!How Angular2 Can Improve Your AngularJS Apps Today!
How Angular2 Can Improve Your AngularJS Apps Today!
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introduction
 
Angular2 - getting-ready
Angular2 - getting-ready Angular2 - getting-ready
Angular2 - getting-ready
 
AngularJS performance & production tips
AngularJS performance & production tipsAngularJS performance & production tips
AngularJS performance & production tips
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Angular2 workshop
Angular2 workshopAngular2 workshop
Angular2 workshop
 
Webstorm
WebstormWebstorm
Webstorm
 
RESTful API 제대로 만들기
RESTful API 제대로 만들기RESTful API 제대로 만들기
RESTful API 제대로 만들기
 
Angularjs - lazy loading techniques
Angularjs - lazy loading techniques Angularjs - lazy loading techniques
Angularjs - lazy loading techniques
 

Similar to Service-Side Development Quick Introduction

How React Native, Appium and me made each other shine @Frontmania 16-11-2018
How React Native, Appium and me made each other shine @Frontmania 16-11-2018How React Native, Appium and me made each other shine @Frontmania 16-11-2018
How React Native, Appium and me made each other shine @Frontmania 16-11-2018Wim Selles
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java DevelopersYakov Fain
 
A gently introduction to AngularJS
A gently introduction to AngularJSA gently introduction to AngularJS
A gently introduction to AngularJSGregor Woiwode
 
Commit University - Exploring Angular 2
Commit University - Exploring Angular 2Commit University - Exploring Angular 2
Commit University - Exploring Angular 2Commit University
 
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Frost
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIVisual Engineering
 
angular fundamentals.pdf angular fundamentals.pdf
angular fundamentals.pdf angular fundamentals.pdfangular fundamentals.pdf angular fundamentals.pdf
angular fundamentals.pdf angular fundamentals.pdfNuttavutThongjor1
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Loiane Groner
 
Serverless Angular, Material, Firebase and Google Cloud applications
Serverless Angular, Material, Firebase and Google Cloud applicationsServerless Angular, Material, Firebase and Google Cloud applications
Serverless Angular, Material, Firebase and Google Cloud applicationsLoiane Groner
 
Technozaure - Angular2
Technozaure - Angular2Technozaure - Angular2
Technozaure - Angular2Demey Emmanuel
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express jsAhmed Assaf
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-senseBen Lin
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Ontico
 
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin PovolnyDesign Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin PovolnyManageIQ
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptKaty Slemon
 

Similar to Service-Side Development Quick Introduction (20)

How React Native, Appium and me made each other shine @Frontmania 16-11-2018
How React Native, Appium and me made each other shine @Frontmania 16-11-2018How React Native, Appium and me made each other shine @Frontmania 16-11-2018
How React Native, Appium and me made each other shine @Frontmania 16-11-2018
 
ParisJS #10 : RequireJS
ParisJS #10 : RequireJSParisJS #10 : RequireJS
ParisJS #10 : RequireJS
 
What is your money doing?
What is your money doing?What is your money doing?
What is your money doing?
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java Developers
 
A gently introduction to AngularJS
A gently introduction to AngularJSA gently introduction to AngularJS
A gently introduction to AngularJS
 
Commit University - Exploring Angular 2
Commit University - Exploring Angular 2Commit University - Exploring Angular 2
Commit University - Exploring Angular 2
 
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
 
angular fundamentals.pdf angular fundamentals.pdf
angular fundamentals.pdf angular fundamentals.pdfangular fundamentals.pdf angular fundamentals.pdf
angular fundamentals.pdf angular fundamentals.pdf
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018
 
Serverless Angular, Material, Firebase and Google Cloud applications
Serverless Angular, Material, Firebase and Google Cloud applicationsServerless Angular, Material, Firebase and Google Cloud applications
Serverless Angular, Material, Firebase and Google Cloud applications
 
Angular js
Angular jsAngular js
Angular js
 
Technozaure - Angular2
Technozaure - Angular2Technozaure - Angular2
Technozaure - Angular2
 
Angular2 + rxjs
Angular2 + rxjsAngular2 + rxjs
Angular2 + rxjs
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
 
AngularJs-training
AngularJs-trainingAngularJs-training
AngularJs-training
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-sense
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
 
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin PovolnyDesign Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescript
 

More from Nir Kaufman

Angular Prestige: Less-known API and techniques
Angular Prestige: Less-known API and techniquesAngular Prestige: Less-known API and techniques
Angular Prestige: Less-known API and techniquesNir Kaufman
 
Angular CLI custom builders
Angular CLI custom buildersAngular CLI custom builders
Angular CLI custom buildersNir Kaufman
 
Electronic music 101 for developers
Electronic music 101 for developersElectronic music 101 for developers
Electronic music 101 for developersNir Kaufman
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass SlidesNir Kaufman
 
Redux pattens - JSHeroes 2018
Redux pattens - JSHeroes 2018Redux pattens - JSHeroes 2018
Redux pattens - JSHeroes 2018Nir Kaufman
 
Angular EE - Special Workshop by Nir Kaufman
Angular EE - Special Workshop by Nir KaufmanAngular EE - Special Workshop by Nir Kaufman
Angular EE - Special Workshop by Nir KaufmanNir Kaufman
 
Boosting Angular runtime performance
Boosting Angular runtime performanceBoosting Angular runtime performance
Boosting Angular runtime performanceNir Kaufman
 
Decorators in js
Decorators in jsDecorators in js
Decorators in jsNir Kaufman
 
Styling recipes for Angular components
Styling recipes for Angular componentsStyling recipes for Angular components
Styling recipes for Angular componentsNir Kaufman
 
Introduction To Angular's reactive forms
Introduction To Angular's reactive formsIntroduction To Angular's reactive forms
Introduction To Angular's reactive formsNir Kaufman
 

More from Nir Kaufman (10)

Angular Prestige: Less-known API and techniques
Angular Prestige: Less-known API and techniquesAngular Prestige: Less-known API and techniques
Angular Prestige: Less-known API and techniques
 
Angular CLI custom builders
Angular CLI custom buildersAngular CLI custom builders
Angular CLI custom builders
 
Electronic music 101 for developers
Electronic music 101 for developersElectronic music 101 for developers
Electronic music 101 for developers
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
 
Redux pattens - JSHeroes 2018
Redux pattens - JSHeroes 2018Redux pattens - JSHeroes 2018
Redux pattens - JSHeroes 2018
 
Angular EE - Special Workshop by Nir Kaufman
Angular EE - Special Workshop by Nir KaufmanAngular EE - Special Workshop by Nir Kaufman
Angular EE - Special Workshop by Nir Kaufman
 
Boosting Angular runtime performance
Boosting Angular runtime performanceBoosting Angular runtime performance
Boosting Angular runtime performance
 
Decorators in js
Decorators in jsDecorators in js
Decorators in js
 
Styling recipes for Angular components
Styling recipes for Angular componentsStyling recipes for Angular components
Styling recipes for Angular components
 
Introduction To Angular's reactive forms
Introduction To Angular's reactive formsIntroduction To Angular's reactive forms
Introduction To Angular's reactive forms
 

Recently uploaded

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 

Recently uploaded (20)

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 

Service-Side Development Quick Introduction

  • 3. Nir Kaufman Head of AngularJS development department @ Nir@500tech.com
  • 4. We will cover: services - definition dependency injection services types common patterns
  • 5. all examples and reference code are written in ES6
  • 7. the term ‘services’ refers to injectable objects whose API is defined by the developer (not the framework)
  • 8. services contain reusable business logic independent of views
  • 9. each service starts as a plain javaScript! object, function or primitive
  • 10. we use one of the module methods to register! our code as a service
  • 11. now we can inject it into other angular components like controllers, directives & services
  • 13. let’s take a high level overview of dependency injection in angular!
  • 14. the key players are the provide & injector! services
  • 15. we register our code on the injector with the provide service https://docs.angularjs.org/api/auto/service/$provide
  • 16. we need to provide a key as the first argument
  • 17. the injector keeps our code in an internal object called providerCache angular source code, line 3926
  • 18. we use the injector retrieve object instances https://docs.angularjs.org/api/auto/service/$injector
  • 19. the first time we inject a service, the injector evaluates the code and stores the result in an instanceCach object
  • 20. the next time that we inject the same service, the injector will first look in the instanceCache angular source code, line 3940
  • 21. that’s why our services are singletons
  • 22. we can’t use a service in the module config phase because the instanceCache is empty until the service is injected for the first time
  • 24. We don’t need to use the provider directly. The module exposes the necessary methods. https://docs.angularjs.org/api/ng/type/angular.Module
  • 25. the module exposes 5 methods used to instruct the injector how to evaluate our code
  • 26. .provider! an object with a $get method.
  • 27. module.provider Construction function for creating new instance of the service. class Logger { ! constructor() { ! let logToConsole = false; ! this.enableConsole = function (flag) { logToConsole = flag; }; ! this.$get = function() { return { debug: function (msg) { if (logToConsole) { console.log(msg) } } } } } }
  • 28. module.provider use it if you need to config your service before it’s instantiated class Logger { ! constructor() { ! let logToConsole = false; ! this.enableConsole = function (flag) { logToConsole = flag; }; ! this.$get = function() { return { debug: function (msg) { if (logToConsole) { console.log(msg) } } } } } } angular.module('app', []) ! .provider(‘logger’, Logger) .config(function(loggerProvider){ loggerProvider.enableConsole(false); }) ! .run(function(logger){ logger.debug(‘log message'); }); we need to call our service with a ‘Provider’ suffix when injecting into config function.
  • 30. module.service a constructor function that will be instantiated. class Logger { ! constructor() { this.enableConsole = true; } ! debug(msg) { if (this.enableConsole) { console.log(msg) } } }
  • 31. module.service use if your object does not need to be configured. class Logger { ! constructor() { this.enableConsole = true; } ! debug(msg) { if (this.enableConsole) { console.log(msg) } } } angular.module('app', []) ! .service(‘logger’, Logger) ! .run(function(logger){ logger.debug(‘log message'); });
  • 32. .factory! just a plain function
  • 33. module.factory Function for creating new instance of an Object. function logger() { ! return { ! debug: function (msg) { console.log(msg); } } } ! ! ! function logger() { ! return function (flag) { return function (msg) { if (flag) console.log(msg); } } } ! !
  • 34. module.factory if you want to return something other than an Object instance function logger() { ! return { debug: function (msg) { console.log(msg); } } } ! ! function logger() { ! return function (flag) { return function (msg) { if (flag) console.log(msg); } } } ! ! angular.module('app', []) .factory(‘logger’, logger) .run(function(logger){ logger.debug(‘log message'); }); angular.module('app', []) ! .factory(‘logger’, logger) .run(function(logger){ logger(true)(‘log message'); });
  • 35. .value! a value of any type
  • 36. module.value Service instance object. registered “as-is”. function randomise() { return Math.random() * 10; } ! var id = 52334556; ! var product = {id: 52345, inStock: true}; ! ! class User { ! constructor(name) { this.firstName = name; } }
  • 37. module.value use it when you need a simple object or primitive. function randomise() { return Math.random() * 10; } ! ! ! ! ! ! ! ! class User { ! constructor(name) { this.firstName = name; } } angular.module('app', []) ! .value(‘randomise’, randomise) ! .run(function(randomise){ var num = randomise() }); angular.module('app', []) ! .value(‘User’, User) ! .run(function(user){ var joe = new User(‘joe’) });
  • 38. .constant! a value of any type
  • 39. module.constant Constant value. registered on the injector instanceCache. var SERVERS = { DEVELOPMENT : "http://localhost:8080/app", DEBUGGING : "http://localhost:5789", PRODUCTION : "http://application.com" }; angular.module('app', []) .constant('SERVERS', SERVERS) ! .config(function (SERVERS) { console.log(SERVERS.PRODUCTION); }) ! .run(function (SERVERS) { console.log(SERVERS.DEVELOPMENT); }); because constants are registered on the injector instanceCache, they can be injected into the config function.
  • 40. service and factory are shorthands for providers class Logger { ! constructor() { ! let logToConsole = false; ! this.enableConsole = function (flag) { logToConsole = flag; }; ! this.$get = ! function () { return { debug: function (msg) { if (logToConsole) { console.log(msg) } } } } } } Provider Factory Service
  • 42. Problem:! I want to decide which service to inject dynamically.
  • 43. Solution:! use the $injector service to grab an instance of the service you need.
  • 44. show me some code! class Logger { ! constructor($injector) { this.injector = $injector; } ! debug(msg, useLogService) { useLogService ? this.injector.get('$log').debug(msg) : console.log(msg); } } angular.module('app', []) ! .service('logger', ['$injector', Logger]) ! .run(function (logger) { logger.debug('something to debug', true) }); dynamic-inject.js
  • 45. Problem:! I want to be able to extend an existing service.
  • 46. Solution:! Services are plain javaScript objects. Prototypal inheritance works as usual.
  • 47. show me some code! class ItemList { ! constructor() { this.items = []; } ! addItem(item) { this.items.push(item); } ! removeItem(item){ this.items.splice(this.items.indexOf(item), 1); } } !! class TaskList extends ItemList { ! constructor() { super() } ! getItems () { return this.items; } } angular.module('app', []) ! .service('taskList', TaskList) prototype-inheritance.js ! .run(function (taskList) { taskList.addItem("some item to be added"); console.log(taskList.getItems()); });
  • 48. Problem:! I want to be able to extend core angular or 3rd party services.
  • 49. Solution:! use the $decorator method to extend or override services.
  • 50. show me some code! function logDecorator($delegate) { ! $delegate.debug = function (msg) { let time = new Date().getTime(); console.log(time + " : " + msg); }; ! return $delegate } ! export default logDecorator; decorator.js angular.module('app', []) ! .config(['$provide', function ($provide) { $provide.decorator('$log', logDecorator) }]) ! .run(['$log', function ($log){ $log.debug('logging with timestamp!'); }]);
  • 51. Problem:! I want to register new services at runtime (lazy register)
  • 52. Solution:! get a reference to the $provide service and use it outside the config block
  • 53. show me some code! class Product { ! constructor(type) { this.productType = type; } ! getType () { return this.productType; } } ! class ProductFactory { ! constructor($provider) { ! let provider = $provider; ! this.$get = function () { return { registerProduct : function (type) { provider.value(type, new Product(type)); } } } } } product-factory.js
  • 54. show me some code! angular.module('app', []) ! .provider('productFactory', ['$provide',ProductFactory]) ! .run(function($injector, productFactory) { ! productFactory.registerProduct(‘chair'); ! var theChair = $injector.get(‘chair'); ! console.log(theChair.getType()); }); product-factory.js
  • 55. grab the code https://github.com/nirkaufman/angularjs-services