Service is a class with business logic to perform validation | calculation by
performing an ajax call to RestAPI
Service will separate business logic from UI, this leads to following advantages
1.reusability
business logic will be reusable across components
2.better code maintenance
3.debugging|unit testing business logic will be easy.
Or
The Angular Services are the piece of code or logic that are used to perform some specific task.
A service can contain a value or function or combination of both. The Services in angular are
injected into the application using the dependency injection mechanism
Why do we need a service in Angular?
Whenever you need to reuse the same data and logic across multiple components of your application, then you need to go for angular service. when ever you see the duplicated code across multiple components, then you need to think about refactoring the same logic or data access code into a service.
The logic or data is implemented in a services and the service can be used across multiple components of your angular application. So, services is a mechanism used to share the functionality between the components.
Without Angular Services, you would have to repeat the same logic or code in multiple components wherever you want this code or logic. Now think about the overhead in terms of time and effort required to develop, debug, test and maintain the duplicated code across multiple places instead of having that duplicated code at one central place like a service and reusing that service where required.
steps to work with services
1.create a service syntax: export class <servicename> { ... }
2.consuming service with in component class syntax: class <componentname> { obj=new new <servicename>(); ... }
In the above case unique object of service class will be created to each component, if the requirement is single object to all the components then go with Dependency Injection
The syntax to create angular service is given below.
import { Injectable } from '@angular/core';
@Injectable()
export class EmployeeServie {
}
Command to create a service
ng generate service Employee
Example
Employee-Service.ts
import { Injectable } from '@angular/core';@Injectable({providedIn: 'root'})export class EmployeeService {constructor() { }getEmployeeDetails(): any[] {return [{ID: 'emp101', FirstName: 'Uday', LastName: 'Kumar',Branch: 'CSE', DOB: '29/02/1988', Gender: 'Male'},{ID: 'emp102', FirstName: 'Anurag', LastName: 'Mohanty',Branch: 'ETC', DOB: '23/05/1989', Gender: 'Male'},{ID: 'emp103', FirstName: 'Priyanka', LastName: 'Dewangan',Branch: 'CSE', DOB: '24/07/1992', Gender: 'Female'},{ID: 'emp104', FirstName: 'Hina', LastName: 'Sharma',Branch: 'ETC', DOB: '19/08/1990', Gender: 'Female'},{ID: 'emp105', FirstName: 'Sambit', LastName: 'Satapathy',Branch: 'CSE', DOB: '12/94/1991', Gender: 'Male'}];}}Note: The @Injectable() decorator in angular is used to inject other dependencies into the service. At the moment our service does not have any other dependencies, so, yo can remove the @Injectable() decorator and the service should works.Next step, we are going to use that service in Angular APP.
Three steps , we need to keep in mind before consuming a service
1 Import the service
import { EmployeeService } from '../employee.service';2 Providers( Register the Service)
@Component({selector: 'app-contact',templateUrl: './contact.component.html',styleUrls: ['./contact.component.css'],providers:[EmployeeService]})3 Use the Service
constructor(private _employeeService:EmployeeService) {this.employee=_employeeService.getEmployeeDetails();}
.TS Changes
import { Component } from '@angular/core';import { EmployeeService } from '../employee.service';@Component({selector: 'app-contact',templateUrl: './contact.component.html',styleUrls: ['./contact.component.css'],providers:[EmployeeService]})export class ContactComponent {employee:any[] | undefinedconstructor(private _employeeService:EmployeeService) {this.employee=_employeeService.getEmployeeDetails();}}.html Changes<table><thead><tr><th>ID</th><th>First Name</th><th>Last Name</th><th>Branch</th><th>DOB</th><th>Gender</th></tr></thead><tbody><tr *ngFor='let emp of employee'><td>{{emp.ID}}</td><td>{{emp.FirstName}}</td><td>{{emp.LastName}}</td><td>{{emp.Branch}}</td><td>{{emp.DOB}}</td><td>{{emp.Gender}}</td></tr></tbody></table>
Output
Difference between Constructor vs ngOnInit()The ngOnInit is a method provided by Angular which is called after the constructor and is generally used to perform tasks related to Angular bindings.
ngOnInit is the right place to call a service method to fetch data from a remote server. We can also do the same using a class constructor, but the thumb rule is consuming should use ngOnInit instead of the constructor. As fetching data from a remote server is time consuming, the better place for calling the service method is ngOnInit.
In our example, the dependency injection is done using the class constructor and the actual service method call is issued from ngOnInit life cycle.
No comments:
Post a Comment
Thank you for visiting my blog