SlideShare una empresa de Scribd logo
1 de 23
Service
Factory
Provider
var mi= angular.module('myModule', []);
mi.factory('serviceId', function () {
var shinyNewServiceInstance;
//factory function body that constructs shinyNewServiceInstance
return shinyNewServiceInstance;
});
angular.module('myModule', [], function ($provide) {
$provide.factory('serviceId', function () {
var shinyNewServiceInstance;
//factory function body that constructs shinyNewServiceInstance
return shinyNewServiceInstance;
});
});
angular.module('myApp', [])
.provider('myPro', function() {
console.log('myApp => Create provider => retrun object with $get');
return {
isTrue: false,
$get: function b($log) {
var self = this;
console.log('myApp => my Provider $get => retrun func');
return function c(msg) {
$log.debug(msg + " isTrue: " + self.isTrue);
};
}
};
});
Step 1: Invoke the function
before the config stage. No
args.
app.config(function (myProProvider) {
myProProvider.isTrue = true;
console.log('myApp --> config');
});
Step 2: This object will be
available in config stage as
injectable service. The name
is "myProProvider".
Step 3: $get func is
a factory func for the
service, invoke only if
needed and only
once. Available after
the config stage.
Step 4: The injectable service.
Angular register your provider ( {..} | f )
Module Config( {..} )
Execute the $get function
Decorator stage
Module Run( {..} | f )
function provider(name, provider_) {
if (isFunction(provider_) || isArray(provider_)) {
provider_ = providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw Error(...'must define $get factory method.');
}
return providerCache[name + providerSuffix] = provider_;
}
// Register an object provider
myApp.provider('awesome', {
$get: function () {
return 'awesome data';
}
});
Step 1: Invoke the function
before the config stage. No
args.
Step 2: This object will be
available in config stage as
injectable service. The name
is "[name + providerSuffix]".
angular.module('myApp', [])
.factory('myfac', function ($http) {
console.log('myApp -> Create factory');
return function (msg) {
console.log(msg);
};
});
Step 2: The injectable service.
Step 1: factory func for the service,
invoke only if needed and only once.
Available after the config stage.
app.run(function ( myfac ){
console.log('myApp --> run');
myfac("test");
});
function factory(name, factoryFn) {
return provider(name, { $get: factoryFn });
}
// Sample Code
angular.module('myApp', [])
.factory('myfac', function ($http) {
console.log('myApp -> Create factory');
return function (msg) {
console.log(msg);
};
});
function factory(name, factoryFn) {
return provider(name, { $get: factoryFn });
}
// Sample Code
angular.module('myApp', [])
.provider('myfac', { $get : function ($http) {
console.log('myApp -> Create factory');
return function (msg) {
console.log(msg);
};
}
}
);
function MyService($http) {
console.log('Create my Service => retrun object this.');
this.msg = 'NAN';
}
MyService.prototype.log = function (val) {
console.log(this.msg + val );
};
angular.module('myApp', []).service( 'myService', MyService );
 Angular use the new operator to create instance.
 The return object (this) is the singleton service.
 Everything that uses the service will get the same
instance!
function service(name, constructor) {
return factory(name, ['$injector', function ($injector) {
// instantiated with the new operator
return $injector.instantiate(constructor);
}]);
}
 Angular use the new operator to create instance.
 The return object (this) is the singleton service.
 Everything that uses the service will get the same
instance!
function service(name, constructor) {
return provider(name, {
$get: ['$injector', function ($injector) {
// instantiated with the new operator
return $injector.instantiate(constructor);
}]
});
}
 Angular use the new operator to create instance.
 The return object (this) is the singleton service.
 Everything that uses the service will get the same
instance!
function value(name, value) {
return factory(name, valueFn(value));
}
// Sample Code
myApp.value('awesome', 'awesome data');
function valueFn(value) {return function() {return value;};}
// Sample Code
angular.module('myApp', [])
.constant('PI', 3.14)
.config(function (PI) { ... });
// AngularJS Constant Code
function constant(name, value) {
providerCache[name] = value;
instanceCache[name] = value;
}
Angular register your provider ( {..} | f )
Module Config( {..} )
Execute the $get function
Decorator stage
Module Run( {..} | f )
// Sample Code
$provide.decorator('$log', function ($delegate, $http) {
$delegate.warn = $delegate.error;
return $delegate;
});
$log
You can ask
any service
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 }
);
};
}
Override the $get function.
Invoke the decoFn with
original service instance as
argument.
eyalvardi.wordpress.com

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Pentest Application With GraphQL | Null Bangalore Meetup
Pentest Application With GraphQL | Null Bangalore Meetup Pentest Application With GraphQL | Null Bangalore Meetup
Pentest Application With GraphQL | Null Bangalore Meetup
 
Javascript
JavascriptJavascript
Javascript
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3
 
Java web services using JAX-WS
Java web services using JAX-WSJava web services using JAX-WS
Java web services using JAX-WS
 
Angular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariAngular Introduction By Surekha Gadkari
Angular Introduction By Surekha Gadkari
 
Geb with spock
Geb with spockGeb with spock
Geb with spock
 
Frida Android run time hooking - Bhargav Gajera & Vitthal Shinde
Frida  Android run time hooking - Bhargav Gajera & Vitthal ShindeFrida  Android run time hooking - Bhargav Gajera & Vitthal Shinde
Frida Android run time hooking - Bhargav Gajera & Vitthal Shinde
 
Angular 6 - The Complete Guide
Angular 6 - The Complete GuideAngular 6 - The Complete Guide
Angular 6 - The Complete Guide
 
Node JS reverse shell
Node JS reverse shellNode JS reverse shell
Node JS reverse shell
 
Introduction to Selenium | Selenium Tutorial for Beginners | Selenium Trainin...
Introduction to Selenium | Selenium Tutorial for Beginners | Selenium Trainin...Introduction to Selenium | Selenium Tutorial for Beginners | Selenium Trainin...
Introduction to Selenium | Selenium Tutorial for Beginners | Selenium Trainin...
 
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
 
Typescript Fundamentals
Typescript FundamentalsTypescript Fundamentals
Typescript Fundamentals
 
Vue js for beginner
Vue js for beginner Vue js for beginner
Vue js for beginner
 
Cross browser testing with browser stack
Cross browser testing with browser stackCross browser testing with browser stack
Cross browser testing with browser stack
 
AngularJs presentation
AngularJs presentation AngularJs presentation
AngularJs presentation
 
Selenium WebDriver training
Selenium WebDriver trainingSelenium WebDriver training
Selenium WebDriver training
 
Introducing Swagger
Introducing SwaggerIntroducing Swagger
Introducing Swagger
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data Access
 
Spring Boot 소개
Spring Boot 소개Spring Boot 소개
Spring Boot 소개
 

Destacado

Destacado (16)

AngularJS Compile Process
AngularJS Compile ProcessAngularJS Compile Process
AngularJS Compile Process
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview Questions29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview Questions
 
OOP in JavaScript
OOP in JavaScriptOOP in JavaScript
OOP in JavaScript
 
Services Factory Provider Value Constant - AngularJS
Services Factory Provider Value Constant - AngularJSServices Factory Provider Value Constant - AngularJS
Services Factory Provider Value Constant - AngularJS
 
AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource Services
 
AngulrJS Overview
AngulrJS OverviewAngulrJS Overview
AngulrJS Overview
 
HTTP Interceptors com AngularJS
HTTP Interceptors com AngularJSHTTP Interceptors com AngularJS
HTTP Interceptors com AngularJS
 
AngularJS Routing
AngularJS RoutingAngularJS Routing
AngularJS Routing
 
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
 
Node.js - #7 - Core Modules - http - Parte 1 - Rodrigo Branas
Node.js - #7 - Core Modules - http - Parte 1 - Rodrigo BranasNode.js - #7 - Core Modules - http - Parte 1 - Rodrigo Branas
Node.js - #7 - Core Modules - http - Parte 1 - Rodrigo Branas
 
Forms in AngularJS
Forms in AngularJSForms in AngularJS
Forms in AngularJS
 
Single Page Application (SPA) using AngularJS
Single Page Application (SPA) using AngularJSSingle Page Application (SPA) using AngularJS
Single Page Application (SPA) using AngularJS
 
Angular 2 어디까지 왔을까
Angular 2 어디까지 왔을까Angular 2 어디까지 왔을까
Angular 2 어디까지 왔을까
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get started
 
Angularjs 도입 선택 가이드
Angularjs 도입 선택 가이드Angularjs 도입 선택 가이드
Angularjs 도입 선택 가이드
 

Similar a AngularJS $Provide Service

Similar a AngularJS $Provide Service (20)

ngMess: AngularJS Dependency Injection
ngMess: AngularJS Dependency InjectionngMess: AngularJS Dependency Injection
ngMess: AngularJS Dependency Injection
 
Technozaure - Angular2
Technozaure - Angular2Technozaure - Angular2
Technozaure - Angular2
 
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
 
AngularJs-training
AngularJs-trainingAngularJs-training
AngularJs-training
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
 
"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 - Services
AngularJS - ServicesAngularJS - Services
AngularJS - Services
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
ChtiJUG - Introduction à Angular2
ChtiJUG - Introduction à Angular2ChtiJUG - Introduction à Angular2
ChtiJUG - Introduction à Angular2
 
Modules and injector
Modules and injectorModules and injector
Modules and injector
 
Dependency Injection @ AngularJS
Dependency Injection @ AngularJSDependency Injection @ AngularJS
Dependency Injection @ AngularJS
 
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
 
Explaination of angular
Explaination of angularExplaination of angular
Explaination of angular
 
Complex Sites with Silex
Complex Sites with SilexComplex Sites with Silex
Complex Sites with Silex
 
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
 
AngularJs
AngularJsAngularJs
AngularJs
 
How to build an AngularJS backend-ready app WITHOUT BACKEND
How to build an AngularJS backend-ready app WITHOUT BACKEND How to build an AngularJS backend-ready app WITHOUT BACKEND
How to build an AngularJS backend-ready app WITHOUT BACKEND
 
ZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperZF2 for the ZF1 Developer
ZF2 for the ZF1 Developer
 
Pengenalan blaast platform sdk
Pengenalan blaast platform sdkPengenalan blaast platform sdk
Pengenalan blaast platform sdk
 

Más de Eyal Vardi

Más de Eyal Vardi (20)

Why magic
Why magicWhy magic
Why magic
 
Smart Contract
Smart ContractSmart Contract
Smart Contract
 
Rachel's grandmother's recipes
Rachel's grandmother's recipesRachel's grandmother's recipes
Rachel's grandmother's recipes
 
Performance Optimization In Angular 2
Performance Optimization In Angular 2Performance Optimization In Angular 2
Performance Optimization In Angular 2
 
Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)
 
Angular 2 NgModule
Angular 2 NgModuleAngular 2 NgModule
Angular 2 NgModule
 
Upgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.xUpgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.x
 
Angular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time CompilationAngular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time Compilation
 
Routing And Navigation
Routing And NavigationRouting And Navigation
Routing And Navigation
 
Angular 2 Architecture
Angular 2 ArchitectureAngular 2 Architecture
Angular 2 Architecture
 
Angular 2.0 Views
Angular 2.0 ViewsAngular 2.0 Views
Angular 2.0 Views
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
 
Template syntax in Angular 2.0
Template syntax in Angular 2.0Template syntax in Angular 2.0
Template syntax in Angular 2.0
 
Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0
 
Angular 2.0 Dependency injection
Angular 2.0 Dependency injectionAngular 2.0 Dependency injection
Angular 2.0 Dependency injection
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and Navigation
 
Async & Parallel in JavaScript
Async & Parallel in JavaScriptAsync & Parallel in JavaScript
Async & Parallel in JavaScript
 
Angular 2.0 Pipes
Angular 2.0 PipesAngular 2.0 Pipes
Angular 2.0 Pipes
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
Modules in ECMAScript 6.0
Modules in ECMAScript 6.0Modules in ECMAScript 6.0
Modules in ECMAScript 6.0
 

Último

+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@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
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
 

Último (20)

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
+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...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
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
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
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
 
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
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
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
 

AngularJS $Provide Service

  • 1.
  • 2.
  • 4. var mi= angular.module('myModule', []); mi.factory('serviceId', function () { var shinyNewServiceInstance; //factory function body that constructs shinyNewServiceInstance return shinyNewServiceInstance; }); angular.module('myModule', [], function ($provide) { $provide.factory('serviceId', function () { var shinyNewServiceInstance; //factory function body that constructs shinyNewServiceInstance return shinyNewServiceInstance; }); });
  • 5.
  • 6. angular.module('myApp', []) .provider('myPro', function() { console.log('myApp => Create provider => retrun object with $get'); return { isTrue: false, $get: function b($log) { var self = this; console.log('myApp => my Provider $get => retrun func'); return function c(msg) { $log.debug(msg + " isTrue: " + self.isTrue); }; } }; }); Step 1: Invoke the function before the config stage. No args. app.config(function (myProProvider) { myProProvider.isTrue = true; console.log('myApp --> config'); }); Step 2: This object will be available in config stage as injectable service. The name is "myProProvider". Step 3: $get func is a factory func for the service, invoke only if needed and only once. Available after the config stage. Step 4: The injectable service.
  • 7. Angular register your provider ( {..} | f ) Module Config( {..} ) Execute the $get function Decorator stage Module Run( {..} | f )
  • 8.
  • 9. function provider(name, provider_) { if (isFunction(provider_) || isArray(provider_)) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { throw Error(...'must define $get factory method.'); } return providerCache[name + providerSuffix] = provider_; } // Register an object provider myApp.provider('awesome', { $get: function () { return 'awesome data'; } }); Step 1: Invoke the function before the config stage. No args. Step 2: This object will be available in config stage as injectable service. The name is "[name + providerSuffix]".
  • 10. angular.module('myApp', []) .factory('myfac', function ($http) { console.log('myApp -> Create factory'); return function (msg) { console.log(msg); }; }); Step 2: The injectable service. Step 1: factory func for the service, invoke only if needed and only once. Available after the config stage. app.run(function ( myfac ){ console.log('myApp --> run'); myfac("test"); });
  • 11. function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); } // Sample Code angular.module('myApp', []) .factory('myfac', function ($http) { console.log('myApp -> Create factory'); return function (msg) { console.log(msg); }; });
  • 12. function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); } // Sample Code angular.module('myApp', []) .provider('myfac', { $get : function ($http) { console.log('myApp -> Create factory'); return function (msg) { console.log(msg); }; } } );
  • 13. function MyService($http) { console.log('Create my Service => retrun object this.'); this.msg = 'NAN'; } MyService.prototype.log = function (val) { console.log(this.msg + val ); }; angular.module('myApp', []).service( 'myService', MyService );  Angular use the new operator to create instance.  The return object (this) is the singleton service.  Everything that uses the service will get the same instance!
  • 14. function service(name, constructor) { return factory(name, ['$injector', function ($injector) { // instantiated with the new operator return $injector.instantiate(constructor); }]); }  Angular use the new operator to create instance.  The return object (this) is the singleton service.  Everything that uses the service will get the same instance!
  • 15. function service(name, constructor) { return provider(name, { $get: ['$injector', function ($injector) { // instantiated with the new operator return $injector.instantiate(constructor); }] }); }  Angular use the new operator to create instance.  The return object (this) is the singleton service.  Everything that uses the service will get the same instance!
  • 16. function value(name, value) { return factory(name, valueFn(value)); } // Sample Code myApp.value('awesome', 'awesome data'); function valueFn(value) {return function() {return value;};}
  • 17. // Sample Code angular.module('myApp', []) .constant('PI', 3.14) .config(function (PI) { ... }); // AngularJS Constant Code function constant(name, value) { providerCache[name] = value; instanceCache[name] = value; }
  • 18.
  • 19. Angular register your provider ( {..} | f ) Module Config( {..} ) Execute the $get function Decorator stage Module Run( {..} | f )
  • 20. // Sample Code $provide.decorator('$log', function ($delegate, $http) { $delegate.warn = $delegate.error; return $delegate; }); $log You can ask any service
  • 21. 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 } ); }; } Override the $get function. Invoke the decoFn with original service instance as argument.
  • 22.