grade.service.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { Injectable } from '@angular/core';
  2. import {HttpClient, HttpHeaders} from "@angular/common/http";
  3. import {Grade} from "./grade.model";
  4. import {catchError, Observable, of} from "rxjs";
  5. const httpOptions = {
  6. headers: new HttpHeaders({'Content-Type': 'application/json'})
  7. }
  8. @Injectable({
  9. providedIn: 'root'
  10. })
  11. export class GradeService {
  12. private gradesUrl = 'http://localhost:8080/grades';
  13. constructor(private http: HttpClient) { }
  14. addGrade(grade: Grade): Observable<Grade> {
  15. return this.http.post<Grade>(this.gradesUrl, grade, httpOptions).pipe(
  16. catchError(this.handleError<Grade>('addGrade', 'Error while adding the grade!'))
  17. );
  18. }
  19. getGradesFromSubject(subjectId: number): Observable<Grade[]> {
  20. return this.http.get<Grade[]>(`${this.gradesUrl}/subject/${subjectId}`).pipe(
  21. catchError(this.handleError<Grade[]>('getGradesFromSubject', 'Error while getting grades', []))
  22. );
  23. }
  24. getStudentGrades(): Observable<Grade[]> {
  25. return this.http.get<Grade[]>(`${this.gradesUrl}/student`).pipe(
  26. catchError(this.handleError<Grade[]>('getStudentGrades', 'Error while getting grades!',[]))
  27. );
  28. }
  29. editGrade(grade: Grade): Observable<Grade> {
  30. return this.http.patch<Grade>(`${this.gradesUrl}/edit/${grade.id}`, grade.grade, httpOptions).pipe(
  31. catchError(this.handleError<Grade>('editGrade', 'Editing grade failed!'))
  32. );
  33. }
  34. deleteGrade(id: number): Observable<void> {const url = `${this.gradesUrl}/${id}`;
  35. return this.http.delete<void>(url, httpOptions).pipe(
  36. catchError(this.handleError<void>('deleteGrade', 'Error while deleting the grade!'))
  37. );
  38. }
  39. private handleError<T>(operation = 'operation', communicate: string, result?: T) {
  40. return (error: any): Observable<T> => {
  41. this.log(`${operation} failed: ${error.message}`);
  42. alert(`${communicate}`);
  43. return of(result as T);
  44. };
  45. }
  46. private log(message: string) {
  47. console.log('GradeService: ' + message);
  48. }
  49. }