Using Angular Services
Angular Services can be injected into components and other Angular classes to provide reusable functionality such as data access, business logic, API communication, and shared application state.
What Does Using a Service Mean?
After creating a service, a component can request that service through Angular's dependency injection system.
The component can then call service methods and use the data or functionality provided by the service.
Simple Definition
Using a service means injecting the service into a component and calling its methods whenever the component needs its functionality.
Using a Service Flow
1. Injecting a Service into a Component
A service can be injected into a component constructor. Angular's dependency injection system provides the service instance.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CourseService {
getCourseName(): string {
return 'Angular Full Stack';
}
}
import { Component } from '@angular/core';
import { CourseService } from './course.service';
@Component({
selector: 'app-course',
templateUrl: './course.component.html'
})
export class CourseComponent {
constructor(
private courseService: CourseService
) {
}
}
How it works
Angular detects that the component requires CourseService and provides its available service instance through dependency injection.
2. Calling a Service Method
After injecting the service, the component can call the methods provided by that service.
courseName = '';
constructor(
private courseService: CourseService
) {
}
loadCourse(): void {
this.courseName =
this.courseService.getCourseName();
}
<button
class="btn btn-primary"
(click)="loadCourse()">
Load Course
</button>
<p>
Course:
{{ courseName }}
</p>
Course: Angular Full Stack
3. Using Multiple Service Methods
A component can use multiple methods from the same service.
@Injectable({
providedIn: 'root'
})
export class TrainingService {
getCourseName(): string {
return 'Python Full Stack';
}
getDuration(): string {
return '5 Months';
}
getMode(): string {
return 'Online + Offline';
}
}
courseName = '';
duration = '';
mode = '';
constructor(
private trainingService: TrainingService
) {
}
loadCourseDetails(): void {
this.courseName =
this.trainingService.getCourseName();
this.duration =
this.trainingService.getDuration();
this.mode =
this.trainingService.getMode();
}
Course: Python Full Stack
Duration: 5 Months
Mode: Online + Offline
4. Using a Service in ngOnInit()
A service is often used during component initialization to load initial application data.
import { Component, OnInit } from '@angular/core';
import { TrainingService } from './training.service';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html'
})
export class DashboardComponent implements OnInit {
courses: string[] = [];
constructor(
private trainingService: TrainingService
) {
}
ngOnInit(): void {
this.courses =
this.trainingService.getCourses();
}
}
<h3>
Available Courses
</h3>
<ul>
<li *ngFor="let course of courses">
{{ course }}
</li>
</ul>
Typical Pattern
The component receives the service through dependency injection and calls the service method from ngOnInit() to prepare the initial data.
5. Using a Service That Returns an Array
Services can return arrays that can be displayed by components.
@Injectable({
providedIn: 'root'
})
export class CourseService {
private courses: string[] = [
'Java Full Stack',
'Python Full Stack',
'Full Stack .NET',
'Data Analytics',
'Data Science'
];
getCourses(): string[] {
return this.courses;
}
}
courses: string[] = [];
constructor(
private courseService: CourseService
) {
}
ngOnInit(): void {
this.courses =
this.courseService.getCourses();
}
- Java Full Stack
- Python Full Stack
- Full Stack .NET
- Data Analytics
- Data Science
6. Passing Parameters to Service Methods
Service methods can accept parameters when a component needs dynamic functionality.
getCourseMessage(courseName: string): string {
return 'Selected Course: ' + courseName;
}
message = '';
constructor(
private courseService: CourseService
) {
}
selectCourse(course: string): void {
this.message =
this.courseService
.getCourseMessage(course);
}
<button
class="btn btn-primary"
(click)="selectCourse('Full Stack .NET')">
Select Course
</button>
<p>
{{ message }}
</p>
7. Using an API Service
A service can use HttpClient to communicate with a backend API. Components can then subscribe to the returned Observable.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class CourseService {
private apiUrl =
'https://api.example.com/courses';
constructor(
private http: HttpClient
) {
}
getCourses() {
return this.http.get(this.apiUrl);
}
}
courses: any[] = [];
constructor(
private courseService: CourseService
) {
}
ngOnInit(): void {
this.courseService
.getCourses()
.subscribe(data => {
this.courses = data;
});
}
8. Using the Same Service in Multiple Components
A service can be injected into more than one component when those components need the same functionality.
9. Common Service Responsibilities
Get Data
Retrieve application data from local or remote sources.
getCourses()
Create Data
Send or prepare new application data.
addCourse()
Update Data
Update existing application information.
updateCourse()
Delete Data
Remove application data through reusable service methods.
deleteCourse()
Complete CIIT Training Institute Example
Suppose the CIIT Training Institute dashboard needs to display available courses and training modes. The component can obtain this information from a reusable service.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class TrainingService {
getInstituteName(): string {
return 'CIIT Training Institute';
}
getCourses(): string[] {
return [
'Java Full Stack',
'Python Full Stack',
'Full Stack .NET',
'Data Analytics'
];
}
getTrainingModes(): string[] {
return [
'Online',
'Offline'
];
}
}
import { Component, OnInit } from '@angular/core';
import { TrainingService } from './training.service';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html'
})
export class DashboardComponent implements OnInit {
instituteName = '';
courses: string[] = [];
modes: string[] = [];
constructor(
private trainingService: TrainingService
) {
}
ngOnInit(): void {
this.instituteName =
this.trainingService.getInstituteName();
this.courses =
this.trainingService.getCourses();
this.modes =
this.trainingService.getTrainingModes();
}
}
<h2>
{{ instituteName }}
</h2>
<h4>
Available Courses
</h4>
<ul>
<li *ngFor="let course of courses">
{{ course }}
</li>
</ul>
<h4>
Training Modes
</h4>
<ul>
<li *ngFor="let mode of modes">
{{ mode }}
</li>
</ul>
CIIT Training Institute
Available Courses
- Java Full Stack
- Python Full Stack
- Full Stack .NET
- Data Analytics
Training Modes
- Online
- Offline
Service Usage Checklist
- Inject the required service into the component.
- Store the injected service in a private property.
- Call service methods instead of duplicating reusable logic.
- Use ngOnInit() when initial service data needs to be loaded.
- Subscribe to Observable results when using API-based services.
- Keep UI-specific logic in the component and reusable logic in the service.
Using Services Best Practices
- Inject services instead of creating service objects manually.
- Keep service responsibilities focused and meaningful.
- Do not duplicate the same business logic across components.
- Keep API communication inside dedicated services.
- Use meaningful method names such as getCourses() and getInstituteName().
- Keep components simple by delegating reusable operations to services.
Summary
Angular Services are used by injecting them into components through Angular's dependency injection system.
Once injected, components can call service methods to access data, business logic, API functionality, and other reusable operations.