students.component.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { Component, OnInit } from '@angular/core';
  2. import {Student} from "./student.model";
  3. import {StudentService} from "./student.service";
  4. @Component({
  5. selector: 'app-students',
  6. templateUrl: './students.component.html',
  7. styleUrls: ['./students.component.css']
  8. })
  9. export class StudentsComponent implements OnInit {
  10. studentList?: Student[];
  11. student?: Student;
  12. constructor(private studentService: StudentService) { }
  13. ngOnInit() { this.getStudents(); }
  14. getStudents(): void {
  15. this.studentService.getStudents()
  16. .subscribe(studentList => this.studentList = studentList);
  17. }
  18. add(firstname: string, lastname: string, email: string, telephone: string): void {
  19. firstname = firstname.trim();
  20. lastname = lastname.trim();
  21. email = email.trim();
  22. telephone = telephone.trim();
  23. this.studentService.addStudent({ firstname, lastname, email, telephone } as Student)
  24. .subscribe({
  25. next: (student: Student) => { this.studentList?.push(student); },
  26. error: () => {},
  27. complete: () => {
  28. if (this.studentList != undefined) {
  29. this.studentService.totalItems.next(this.studentList.length);
  30. }
  31. }
  32. });
  33. }
  34. delete(student: Student): void {
  35. this.studentList = this.studentList?.filter(c => c !== student);
  36. this.studentService.deleteStudent(student).subscribe(() => {
  37. // for automatic update of number of students in parent component
  38. if(this.studentList != undefined) {
  39. this.studentService.totalItems.next(this.studentList.length);
  40. }
  41. }
  42. );
  43. }
  44. deleteAll(): void {
  45. this.studentService.deleteStudents().subscribe(() => {
  46. }
  47. );
  48. }
  49. }