Services are same as class with a specific purpose of it. Services can contain method, property and any feature of an application which we can reuse multiple time in our web application. Services also contain a decorator which tell angular how to consume it in our application.
Let’s create a service.
Install a fresh or existing angular project and follow the steps:
Step 1 : Create a service
ng generate service logger
Above code will create a service in src\app\logger.service.ts or we can create manually
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class LoggerService {
constructor() { }
}
Step 2 : Inject service in component
You can inject the service in new component or existing component and can use all the methods and properties of it.
import { Component } from '@angular/core';
import { LoggerService } from './logger.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Service Example';
constructor(logger:LoggerService){
logger.log("This is test")
}
}
Here, we import the LoggerService
and injected it in constructor, then we can use the methods of LoggerService
in this component.
Step 3 : Run and check in console
Run using angular command and check the simple use of services
ng serve
Advantages of service or dependency injection
- Services are globally accessible by angular app
- Using Dependency injection, Angular create the object once and share it with all component so it saves the memory and sustain the state.
- Using Services we can communicate between n level component using EventEmitter.