What is Angular Service?
In simple terms, Angular Service is an object which we can use on multiple places to share a common need, for example, lets we have ten different angular components and we need a logging feature on all/most of them.
The common approach would be adding a method in each component class and using it. This solution will work but this is not an optimized solution.
The other approach could be creating a class and a common method and using its object for the places we need. This is an Angular service.
Why do we need Angular Service?
Now you understood what is angular service. let’s discuss why we need that. you might have already in mind that Angular Services promotes code reusability so it is helpful to developers to easy to implement a common feature and use it in multiple places. On the other side, this helps to find and fix the problems easily as you don’t need to go to all different components and update the code there to fix a problem.
How to create Angular Service?
let’s say you want to log some information to the console from multiple components. This is a perfect candidate to be coded as a service. Let’s take “LoggingService“ as a name for that service.
To create a service name “LoggingService“ you need to go to your application path and run the below command using the terminal/command prompt.


There are two files generated using the above command, the spec.ts is for testing, so let’s leave it for now. The “logger.service.ts“ is the actual service file.
Let’s see what is inside the file.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class LoggerService {
constructor() { }
}

The above is highlighted method which we have added for logging on console for a given message.
“@Injectable“
decorator. This decorator help us to inject the service to components and also to another service. i,e, it helps in dependency injection using Angular framework.Let’s see how?
How to use Angular Service?
To use Angular service you just created follow below steps.
Let’s say you have an “example“ component and you want to log a message on console when a button clicks for that component. You don’t have a component , don’t worry, create it as below.

update “example.component.html“ file as below.

Update “example.component.ts“ file as below.





You may noticed that we are not doing “new“ object here for logger service but Angular is doing dependency injection and will giving us the LoggerService object.
Lets run the project and click on the button.
