SlideShare a Scribd company logo
1 of 40
Download to read offline
ngMess: 
Angular JS DI
Presenter 
Dmitry Ivashutin 
Software Engineer
Dependency Injection 
High-level modules should not depend on 
low-level modules. Both should depend 
on abstractions. 
 Abstractions should not depend on details. 
Details should depend on abstractions.
DI in a Nutshell 
 create the dependency 
 look up the dependency 
 have the dependency injected
The provider
Wiki: The provider 
The $provide service is responsible for telling Angular how 
to create new injectable things; these things are 
called services. Services are defined by things 
called providers, which is what you're creating when you 
use $provide. Defining a provider is done via 
the provider method on the $provide service, and you can 
get hold of the $provide service by asking for it to be injected 
into an application's config function. 
https://github.com/angular/angular.js/wiki/Understanding-Dependency-Injection
How do we usually inject? 
myApp.service('alerter', function () { 
http://jsfiddle.net/ae87/9x7Aq/2/ 
this.sayHello = function(){ 
alert('Hello! '); 
} 
this.sayGoodbye = function(){ 
alert('Goodbye!'); 
} 
});
Let’s start from
Create provider at configure stage 
app.config(function ($provide) { 
$provide.provider('greeting', function () { 
this.$get = function () { 
return function (name) { 
alert('Hello, ' + name); 
}; 
}; 
}); 
});
It’s a valid way
There are other ways
So called “services” 
Factory Service 
Provider 
Value Constant
Calling exact the same code inside 
that we wrote above
Provider way 
function provider(name, provider_) { 
assertNotHasOwnProperty(name, 'service'); 
if (isFunction(provider_) || isArray(provider_)) { 
provider_ 
= providerInjector.instantiate(provider_); 
} 
if (!provider_.$get) 
return providerCache[name + providerSuffix] 
= provider_; 
}
Factory way 
function factory(name, factoryFn) { 
return provider( 
name, 
{ 
$get: factoryFn 
}); 
}
Service way 
function service(name, constructor) { 
return factory( 
name, 
[ 
'$injector', 
function ($injector) { 
return $injector.instantiate(constructor); 
} 
]); 
}
Value way 
function value(name, val) { 
return factory( 
name, 
valueFn(val) 
); 
} 
function valueFn(value) { 
return function () { 
return value; 
}; 
}
Constant way 
function constant(name, value) { 
assertNotHasOwnProperty(name, 'constant'); 
providerCache[name] = value; 
instanceCache[name] = value; 
}
Syntactic sugar
Looks annoying, right? 
app.config(function($provide) { ... })
Module level access 
$provide 
.provider('greeting', ...); 
angular 
.module('myModule', []) 
.provider('greeting', ...);
“A Sound of Thunder”
Service Recipe 
 Utility functions via public API 
 Non-new-able stuff 
Works better for objects of custom type 
service(class) 
– registers a constructor function, 
class that will be wrapped in 
a service provider object
Factory Recipe 
 Exposing public API 
 Constructors via new-able functions 
Can produce JavaScript primitives and functions 
factory(fn) 
– registers a service factory 
function, that will be wrapped 
in a service provider object
Provider Recipe 
 Configurable stuff 
You don't need it unless you are building a 
reusable piece of code that needs global 
configuration 
provider(provider) 
– registers a service provider 
with the $injector
Value Recipe 
 Exposing static values and constants 
value(obj) 
– registers a value/object that 
can only be accessed by 
services, not providers
Constant Recipe 
 Exposing compile time static values and 
constants 
constant(obj) 
– registers a value/object 
that can be accessed by 
providers and services
Decorator
Decorator way 
function decorator(serviceName, decorFn) { 
var origProvider = providerInjector 
.get(serviceName + providerSuffix), 
orig$get = origProvider.$get; 
origProvider.$get = function () { 
var origInstance = instanceInjector 
.invoke(orig$get, origProvider); 
return instanceInjector.invoke( 
decorFn, null, 
{ $delegate: origInstance }); 
}; 
}
Know-how 
app.config(function ($provide) { 
$provide.decorator('$log', function ($delegate) { 
// save the original function 
var _log = $delegate.log; 
// replace the original behavior 
$delegate.log = function (msg) { 
_log(msg); 
alert(msg); 
}; 
return $delegate; 
}); 
}); 
http://plnkr.co/edit/imqmvUfk4oWWuwg75sP1?p=preview
Few more quick facts
Injector: Why 
 Feel the power of DI 
 Control the injection real-time 
 Access DI container from outside of your app 
 Primary usage - testing
Injector: How 
function MyController($scope, $injector) { 
$scope.doSomething = function(someServiceName) { 
// someService contains the name of a service 
var service = $injector.get(someServiceName); 
service.do(); 
}; 
}
Scripts require proper order
The End! Questions?

More Related Content

What's hot

What's hot (20)

Continuous Integration with Gitlab
Continuous Integration with GitlabContinuous Integration with Gitlab
Continuous Integration with Gitlab
 
Cyclejs introduction
Cyclejs introductionCyclejs introduction
Cyclejs introduction
 
Routing And Navigation
Routing And NavigationRouting And Navigation
Routing And Navigation
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
Modules and injector
Modules and injectorModules and injector
Modules and injector
 
jQuery Plugin
jQuery PluginjQuery Plugin
jQuery Plugin
 
AngularJS in practice
AngularJS in practiceAngularJS in practice
AngularJS in practice
 
Angular 1.x vs. Angular 2.x
Angular 1.x vs. Angular 2.xAngular 1.x vs. Angular 2.x
Angular 1.x vs. Angular 2.x
 
Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
RSpec
RSpecRSpec
RSpec
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
Angular 2 Architecture
Angular 2 ArchitectureAngular 2 Architecture
Angular 2 Architecture
 
AngularJS Animations
AngularJS AnimationsAngularJS Animations
AngularJS Animations
 
React native tour
React native tourReact native tour
React native tour
 
Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
Excellent
ExcellentExcellent
Excellent
 

Viewers also liked (6)

AngularJS - dependency injection
AngularJS - dependency injectionAngularJS - dependency injection
AngularJS - dependency injection
 
introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basics
 
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBDynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
 
AngularJS intro
AngularJS introAngularJS intro
AngularJS intro
 
Gettings started with the superheroic JavaScript library AngularJS
Gettings started with the superheroic JavaScript library AngularJSGettings started with the superheroic JavaScript library AngularJS
Gettings started with the superheroic JavaScript library AngularJS
 
Dependency Injection @ AngularJS
Dependency Injection @ AngularJSDependency Injection @ AngularJS
Dependency Injection @ AngularJS
 

Similar to ngMess: AngularJS Dependency Injection

Similar to ngMess: AngularJS Dependency Injection (20)

AngularJs-training
AngularJs-trainingAngularJs-training
AngularJs-training
 
Technozaure - Angular2
Technozaure - Angular2Technozaure - Angular2
Technozaure - Angular2
 
WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto University
 
Getting the Most Out of jQuery Widgets
Getting the Most Out of jQuery WidgetsGetting the Most Out of jQuery Widgets
Getting the Most Out of jQuery Widgets
 
ChtiJUG - Introduction à Angular2
ChtiJUG - Introduction à Angular2ChtiJUG - Introduction à Angular2
ChtiJUG - Introduction à Angular2
 
Explaination of angular
Explaination of angularExplaination of angular
Explaination of angular
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in react
 
"Angular.js Concepts in Depth" by Aleksandar Simović
"Angular.js Concepts in Depth" by Aleksandar Simović"Angular.js Concepts in Depth" by Aleksandar Simović
"Angular.js Concepts in Depth" by Aleksandar Simović
 
AngularJs Crash Course
AngularJs Crash CourseAngularJs Crash Course
AngularJs Crash Course
 
Get AngularJS Started!
Get AngularJS Started!Get AngularJS Started!
Get AngularJS Started!
 
Building an End-to-End AngularJS Application
Building an End-to-End AngularJS ApplicationBuilding an End-to-End AngularJS Application
Building an End-to-End AngularJS Application
 
A resource oriented framework using the DI/AOP/REST triangle
A resource oriented framework using the DI/AOP/REST triangleA resource oriented framework using the DI/AOP/REST triangle
A resource oriented framework using the DI/AOP/REST triangle
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Complex Sites with Silex
Complex Sites with SilexComplex Sites with Silex
Complex Sites with Silex
 
ZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperZF2 for the ZF1 Developer
ZF2 for the ZF1 Developer
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
 
Into the ZF2 Service Manager
Into the ZF2 Service ManagerInto the ZF2 Service Manager
Into the ZF2 Service Manager
 
2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack
 
Restaurant Server - Transcript.pdf
Restaurant Server - Transcript.pdfRestaurant Server - Transcript.pdf
Restaurant Server - Transcript.pdf
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

ngMess: AngularJS Dependency Injection

  • 2. Presenter Dmitry Ivashutin Software Engineer
  • 3. Dependency Injection High-level modules should not depend on low-level modules. Both should depend on abstractions.  Abstractions should not depend on details. Details should depend on abstractions.
  • 4. DI in a Nutshell  create the dependency  look up the dependency  have the dependency injected
  • 6. Wiki: The provider The $provide service is responsible for telling Angular how to create new injectable things; these things are called services. Services are defined by things called providers, which is what you're creating when you use $provide. Defining a provider is done via the provider method on the $provide service, and you can get hold of the $provide service by asking for it to be injected into an application's config function. https://github.com/angular/angular.js/wiki/Understanding-Dependency-Injection
  • 7.
  • 8. How do we usually inject? myApp.service('alerter', function () { http://jsfiddle.net/ae87/9x7Aq/2/ this.sayHello = function(){ alert('Hello! '); } this.sayGoodbye = function(){ alert('Goodbye!'); } });
  • 10. Create provider at configure stage app.config(function ($provide) { $provide.provider('greeting', function () { this.$get = function () { return function (name) { alert('Hello, ' + name); }; }; }); });
  • 12.
  • 14. So called “services” Factory Service Provider Value Constant
  • 15. Calling exact the same code inside that we wrote above
  • 16. Provider way function provider(name, provider_) { assertNotHasOwnProperty(name, 'service'); if (isFunction(provider_) || isArray(provider_)) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) return providerCache[name + providerSuffix] = provider_; }
  • 17. Factory way function factory(name, factoryFn) { return provider( name, { $get: factoryFn }); }
  • 18. Service way function service(name, constructor) { return factory( name, [ '$injector', function ($injector) { return $injector.instantiate(constructor); } ]); }
  • 19. Value way function value(name, val) { return factory( name, valueFn(val) ); } function valueFn(value) { return function () { return value; }; }
  • 20. Constant way function constant(name, value) { assertNotHasOwnProperty(name, 'constant'); providerCache[name] = value; instanceCache[name] = value; }
  • 21.
  • 23. Looks annoying, right? app.config(function($provide) { ... })
  • 24. Module level access $provide .provider('greeting', ...); angular .module('myModule', []) .provider('greeting', ...);
  • 25. “A Sound of Thunder”
  • 26.
  • 27. Service Recipe  Utility functions via public API  Non-new-able stuff Works better for objects of custom type service(class) – registers a constructor function, class that will be wrapped in a service provider object
  • 28. Factory Recipe  Exposing public API  Constructors via new-able functions Can produce JavaScript primitives and functions factory(fn) – registers a service factory function, that will be wrapped in a service provider object
  • 29. Provider Recipe  Configurable stuff You don't need it unless you are building a reusable piece of code that needs global configuration provider(provider) – registers a service provider with the $injector
  • 30. Value Recipe  Exposing static values and constants value(obj) – registers a value/object that can only be accessed by services, not providers
  • 31. Constant Recipe  Exposing compile time static values and constants constant(obj) – registers a value/object that can be accessed by providers and services
  • 33. Decorator way function decorator(serviceName, decorFn) { var origProvider = providerInjector .get(serviceName + providerSuffix), orig$get = origProvider.$get; origProvider.$get = function () { var origInstance = instanceInjector .invoke(orig$get, origProvider); return instanceInjector.invoke( decorFn, null, { $delegate: origInstance }); }; }
  • 34. Know-how app.config(function ($provide) { $provide.decorator('$log', function ($delegate) { // save the original function var _log = $delegate.log; // replace the original behavior $delegate.log = function (msg) { _log(msg); alert(msg); }; return $delegate; }); }); http://plnkr.co/edit/imqmvUfk4oWWuwg75sP1?p=preview
  • 35.
  • 36. Few more quick facts
  • 37. Injector: Why  Feel the power of DI  Control the injection real-time  Access DI container from outside of your app  Primary usage - testing
  • 38. Injector: How function MyController($scope, $injector) { $scope.doSomething = function(someServiceName) { // someService contains the name of a service var service = $injector.get(someServiceName); service.do(); }; }