3. //2015.angularconf.it | #angularconf15
A `Service` to rule them all
• In a world based on DI, separation responsibilities is a key
aspect to:
• Testability
• Reusable code
• Services, or components, exist to:
• Connect different pieces that live at the client;
• Connect the client to the back-end;
• In AngularJS 1.x:
• Services are always registered as singleton;
• `Service`, `Factory` and `Provider` allow the developer take control over
the component registration and instantiation process;
7. //2015.angularconf.it | #angularconf15
Service and Factory
• AngularJS boot is a 2-phase process: `config`, `run`;
• In the `config` phase we can depend on providers
only:
• Providers can depend on other providers;
• If we need to interact/configure a service during
the `config` phase we must use a `Provider`;
• Service or Factory won’t work.
8. //2015.angularconf.it | #angularconf15
Provider: full control
angular.module(`myModule`)
.provider( `myService`, function myServiceProvider( injectable ){
function MyService(){ }
this.$get = function myServiceFactory( injectable ) {
return new MyService();
};
});
`Config`
`Run`
`cache`
9. //2015.angularconf.it | #angularconf15
Issues
• Singletons only
• in AngularJS 1.x the `keyword` determines the lifecycle;
• Namespace collision
• Tight coupling between Angular and the DI
framework
11. //2015.angularconf.it | #angularconf15
Actors
• Injector: APIs to create instances of dependencies
• Provider: a recipe, to tell the injector how to create
an instance of a dependency.
• A provider takes a token and maps that to a factory
function that creates an object.
• Dependency: Describes the type of object that
should be created.