8. Services Basics
Step1: Creating Angular Service
The angular service is composed of three things. You need to create an export class and you need to decorate that class with @Injectable decorator and you need to import the Injectable decorator from the angular core library. The syntax to create angular service is given below.
Let say you want to create an angular service for fetching the student details and this student details is going to be used by many components. So, open terminal and type ng generate service Student and press enter as shown below.
ng generate service student
// student.service.ts
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
@Injectable({
providedIn: 'root', // This ensures that the service is a singleton and can be injected throughout the app.
})
export class StudentService {
private students: Student[] = [
{ id: 1, name: 'John', grade: 'A' },
{ id: 2, name: 'Sarah', grade: 'B' },
{ id: 3, name: 'Mike', grade: 'C' },
// Add more student details here
];
getStudents(): Observable<Student[]> {
return of(this.students);
}
getStudentById(id: number): Observable<Student | undefined> {
const student = this.students.find((s) => s.id === id);
return of(student);
}
}
export interface Student {
id: number;
name: string;
grade: string;
}
In this example, we've created an StudentService class that provides two methods:
getStudents(): This method returns anObservableof an array of students.getStudentById(id): This method takes a student ID as a parameter and returns anObservableof the corresponding student's details.
Now, you can inject this service into your Angular components and use it to fetch student details. Here's an example of how to use this service in a component:
// student.component.ts
import { Component, OnInit } from '@angular/core';
import { StudentService, Student } from './student.service';
@Component({
selector: 'app-student',
templateUrl: './student.component.html',
styleUrls: ['./student.component.css'],
})
export class StudentComponent implements OnInit {
students: Student[] = [];
constructor(private studentService: StudentService) {}
ngOnInit(): void {
this.studentService.getStudents().subscribe((students) => {
this.students = students;
});
}
}
In this component, we inject the StudentService and use the getStudents method to fetch the student details.
Remember to import and include the StudentService in your app module providers, and you can then use it in any other component where you need to access student details.
Comments
Post a Comment