Services in Angular - lordoftheflies/angular-essential-training GitHub Wiki
Services are not an angular construct but rather a pattern. They are nothing more than a class to encapsulate some logic that you want to share across places in your application. With Angular's dependency injection, you can inject services around your application. To create a service class, you do not need to do anything Angular specific. There is no metadata needed. There's not some naming convention requirement, or some functional interface that needs to be implemented. They are just plain old classes that you create to modularize reusable code. There are several reasons why you would want to create and use services in your Angular applications. One of the most common is a data service. A class that will handle getting and setting data from your data store. In the case of the media watch list application, it displays a list of media items, and allows the user to delete and add items. All done from different components. A data service that gets injected into each of those components, allows you to not have to recreate the same data store connection code in each component. Another common use for a service is for some business logic. Let's say you have a ratings calculator that handles a formula for determining a likeability ranking. You can wrap that logic up in a service class and use that across the app in different components, without having to rewrite that formula in each place. The Angular framework has classes that are essentially services classes. Things like Http, FormBuilder, and more, contain logic for doing specific things that are non-component specific. And again, through the dependency injection engine, you can get these services sent into your class constructors and use them. Services provide an architectural way to encapsulate business logic in a reusable fashion. Allowing you to keep that logic out of your components direct as in pipe classes. This is not only beneficial for modularity and single responsibility type of simplicity to your code, but it also makes the code more testable. If you employ a unit testing strategy, it becomes real easy to mock the services that get used in a component. And thus, your unit test can focus purely on confirming the behavior of the component and not as dependencies. Same goes for your services that get other services provided to them. So services, while not an enforced construct, are a fundamental building block to an Angular application.