SlideShare ist ein Scribd-Unternehmen logo
1 von 40
Downloaden Sie, um offline zu lesen
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?

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (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
 

Andere mochten auch (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
 

Ähnlich wie ngMess: AngularJS Dependency Injection

Ähnlich wie 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
 

Kürzlich hochgeladen

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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
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...
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
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
 
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...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

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