Services
- In Angular, services are a fundamental building block that helps you encapsulate and share functionality across different parts of your application.
- Services are singleton objects, meaning there's only one instance of a service created and shared throughout the application.
- This ensures that the data and functions provided by a service are consistent and accessible across components.
Significance of Service
- Code Reusability: Services promote the DRY (Don't Repeat Yourself) principle by allowing you to centralize functionality that is used in multiple parts of your application. This not only makes your codebase cleaner but also simplifies maintenance.
- Data Sharing: Services act as a bridge for communication between different components in Angular. They facilitate the sharing of data and state among components, enabling seamless interaction.
- Injectable Dependencies: Angular services are injectable, meaning they can be injected into components, directives, or other services to provide additional functionality. This promotes a modular and extensible architecture.
- Asynchronous Operations: Services are ideal for handling asynchronous operations, such as making HTTP requests, dealing with timers, or managing events. Their singleton nature ensures consistent behavior across the application.
Example: In the following example we will create a service class so that we can reuse the data in different components of an application. Here, we are fetching the user data with the help of userdata service to the footer of the main application as well as to the content area.
Step 1: Create an Angular project using Angular CLI.
ng new service-example
Step 2: Create a service in the services folder.
ng g service services/userdata
Step 3: Create a function to fetch data to the application in the service.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class UserdataService {
constructor() { }
users() {
return [
{ id: '1', name: "John", age: 25, gender: "male" },
{ id: '2', name: "Jane", age: 30, gender: "female" }
]
}
}
Step 4: After creating the function we will create the footer component so that we will fetch the data from the service to the footer.
ng g c footer
Step 5: Now we will modify the HTML, CSS and Typescript file of the footer so that the fetched data can be shown properly.
<div class="footer">
<h1>Footer</h1>
<ul>
<li *ngFor="let user of users">
{{user.name}}:{{user.age}}
</li>
</ul>
</div>
.footer {
background-color: blueviolet;
bottom: 0;
position: absolute;
width: 99%;
padding: 5px;
color: #fff;
}
import { Component, OnInit } from '@angular/core';
import { UserdataService } from '../services/userdata.service';
@Component({
selector: 'app-footer',
templateUrl: './footer.component.html',
styleUrls: ['./footer.component.css']
})
export class FooterComponent implements OnInit {
users: any;
constructor(private userData: UserdataService) {
console.warn("userdata", userData.users())
this.users = userData.users();
}
}
Step 6: After that, we will modify the ‘app.component.html’ file to add a footer to the main application. Also, here we add the fetched data on the content area as well as in the footer section without copying them to both sections with the use of services.
<h1>{{title}}</h1>
<ul>
<li *ngFor="let user of users">
{{user.name}}
</li>
</ul>
<app-footer></app-footer>
import { Component } from '@angular/core';
import { UserdataService } from './services/userdata.service'
import { Services } from '@angular/core/src/view';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Service-Example';
users: any;
constructor(private userData: UserdataService) {
console.warn("userdata", userData.users())
this.users = userData.users();
}
}
Step 7: Add the service class to 'app.module.ts'
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { FooterComponent } from './footer/footer.component';
import { UserdataService } from './services/userdata.service';
@NgModule({
declarations: [
AppComponent,
FooterComponent
],
imports: [
BrowserModule
],
providers: [UserdataService],
bootstrap: [AppComponent]
})
export class AppModule { }
Step 8: Now run or compile the application.
ng serve
You will see the result on http://localhost:4200