Se ha denunciado esta presentación.
Utilizamos tu perfil de LinkedIn y tus datos de actividad para personalizar los anuncios y mostrarte publicidad más relevante. Puedes cambiar tus preferencias de publicidad en cualquier momento.

AngularJS - Services

2.584 visualizaciones

Publicado el

A presentation made for the AngularJS-IL meetup group that took place in oct 2014 at Google TLV Campus (http://www.meetup.com/AngularJS-IL/events/207559572/)
its an overview of how to use services in your app. this slideshow contain a link for a reference code on github.
(link in the last slide)

Publicado en: Tecnología

AngularJS - Services

  1. 1. service-side development
  2. 2. quick introduction
  3. 3. Nir Kaufman Head of AngularJS development department @ Nir@500tech.com
  4. 4. We will cover: services - definition dependency injection services types common patterns
  5. 5. all examples and reference code are written in ES6
  6. 6. Services defined
  7. 7. the term ‘services’ refers to injectable objects whose API is defined by the developer (not the framework)
  8. 8. services contain reusable business logic independent of views
  9. 9. each service starts as a plain javaScript! object, function or primitive
  10. 10. we use one of the module methods to register! our code as a service
  11. 11. now we can inject it into other angular components like controllers, directives & services
  12. 12. Dependency Injection
  13. 13. let’s take a high level overview of dependency injection in angular!
  14. 14. the key players are the provide & injector! services
  15. 15. we register our code on the injector with the provide service https://docs.angularjs.org/api/auto/service/$provide
  16. 16. we need to provide a key as the first argument
  17. 17. the injector keeps our code in an internal object called providerCache angular source code, line 3926
  18. 18. we use the injector retrieve object instances https://docs.angularjs.org/api/auto/service/$injector
  19. 19. the first time we inject a service, the injector evaluates the code and stores the result in an instanceCach object
  20. 20. the next time that we inject the same service, the injector will first look in the instanceCache angular source code, line 3940
  21. 21. that’s why our services are singletons
  22. 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
  23. 23. registering services
  24. 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. 25. the module exposes 5 methods used to instruct the injector how to evaluate our code
  26. 26. .provider! an object with a $get method.
  27. 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. 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.
  29. 29. .service! plain javaScript Object
  30. 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. 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. 32. .factory! just a plain function
  33. 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. 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. 35. .value! a value of any type
  36. 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. 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. 38. .constant! a value of any type
  39. 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. 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
  41. 41. common patterns
  42. 42. Problem:! I want to decide which service to inject dynamically.
  43. 43. Solution:! use the $injector service to grab an instance of the service you need.
  44. 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. 45. Problem:! I want to be able to extend an existing service.
  46. 46. Solution:! Services are plain javaScript objects. Prototypal inheritance works as usual.
  47. 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. 48. Problem:! I want to be able to extend core angular or 3rd party services.
  49. 49. Solution:! use the $decorator method to extend or override services.
  50. 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. 51. Problem:! I want to register new services at runtime (lazy register)
  52. 52. Solution:! get a reference to the $provide service and use it outside the config block
  53. 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. 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. 55. grab the code https://github.com/nirkaufman/angularjs-services
  56. 56. Thank you.

×