student-info/src/app/student.service.ts
Gal Podlipnik 09a21fdbf2 mvp
2025-06-17 02:10:16 +02:00

60 lines
1.3 KiB
TypeScript

import { Injectable } from '@angular/core';
import { stored } from '@mmstack/primitives';
import { v4 as uuid } from 'uuid';
import generateRandom from './mock';
export type Student = {
id: string;
name: string;
email: string;
courses: string[];
};
@Injectable({
providedIn: 'root',
})
export class StudentService {
students = stored<Student[]>([], {
key: 'students',
});
courses = ['Mathematics', 'Physics', 'Chemistry', 'History', 'Literature'];
addStudent({ name, email, courses }: Omit<Student, 'id'>) {
const newStudent: Student = {
id: uuid(),
name,
email,
courses,
};
this.students.update((students) => [...students, newStudent]);
}
getStudentById(id: string) {
return this.students().find((student) => student.id === id);
}
updateStudent(student: Student) {
this.students.update((students) =>
students.map((s) => (s.id === student.id ? student : s))
);
}
generateMockData() {
const mockData: Student[] = generateRandom();
this.students.set(mockData);
}
updateStudentCourse(id: string, courses: string[]) {
this.students.update((students) =>
students.map((s) => (s.id === id ? { ...s, courses } : s))
);
}
deleteSutdent(id: string) {
this.students.update((students) => students.filter((s) => s.id !== id));
}
}