Services in Angular | Services Create in Angular step by step | Angular 15+
A Service is a re-usable TypeScript class that can be used in multiple components across your Angular application. Services can be used to handle tasks such as data manipulation, data fetching from APIs, communication between components, user authentication, logging, or any other feature that is not directly tied to a single component's view.
- if we have 10 components with 10 buttons <button>Enroll</button>. when user click on it we need to handle logic in every component. this is code duplication and difficult. so we make a new class and use that in every component that need it , to acheive this we need service.
- Also Service get data from backend and used to provide that data to each component that need.
- Using services we can communicate between components without @Input() Or @Output() decorator
Creating A service:
1.create a folder services and run below command inside that folder
ng generate service enroll
2. create method inside service Services/enroll.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class EnrollService {
constructor() { }
onEnrollClick(title:string){
alert("Thanks for enroll in "+title);
}
}
4. Add a new method in component where we want to use service ie app/home/home.component.ts also import service + create instance of service + call method of service
import { Component } from '@angular/core';
import { EnrollService } from '../Services/enroll.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent {
title="Home View";
OnEnroll(){
const enrollService = new EnrollService();
enrollService.onEnrollClick(this.title);
}
}
5. Bind method of component in view ie app/home/home.component.html
<button (click)="OnEnroll()">home works!</button>
Click on this button, it will go to component and component call the serve and get responce.