Angular 2 - Services and other business logic


When we discussed the role of Dependency Injection in Angular, there was a hint at the concept of services. Services in Angular are more of an implied pattern. There is nothing specific in the Angular framework that defines some code as a service. 

We typically refer to a JavaScript class or function that we have written to encapsulate some logic as a service for our application. When you write your components in Angular, it preferred to craft the classes for these in a way that the class logic only consists of brokering data to and from the view and adding functionality to the view. 

So if you don't put application business logic in your components and directives, then where do you put it? The answer is services. So let's say you had a component that needs to display a media item. 

You can write a JavaScript class that handles finding the record data and returning it as an object. This would be a service. And then, using Angular's DI framework, you can specify that your media item component is going to use your service. And from within your component logic, you can request the media item record from your service and make it available to your view template. These services that you write can also leverage DI. 


So you can create constructors and specify parameter types with the help of some TypeScript, and Angular will provide your service instance with the appropriate dependencies. There is nothing in the services that you write that make them any sort of Angular-type service. They are just plain old JavaScript logic code. And with the power of DI, they are given other code to work with without needing to know if that code is Angular-specific code. So when you leverage writing services in your app code, you get the benefit of writing JavaScript logic that is in no way coupled to the Angular framework. 

This is one of the nice advantages of Angular. The framework is designed to use your code. This allows you to write modular decoupled code that is easier to maintain and reuse.