import { Injectable } from '@angular/core' ; import { Student } from './student' ; import { Observable , throwError } from 'rxjs' ; import { catchError , map } from 'rxjs/operators' ; import { HttpClient , HttpHeaders , HttpErrorResponse } from '@angular/common/http' ; @ Injectable ( { providedIn : 'root' } ) export class ApiService { endpoint : string = 'http://localhost:8000/api' ; headers = new HttpHeaders ( ) . set ( 'Content-Type' , 'application/json' ) ; constructor ( private http ) { } AddStudent ( data ) { let API_URL = `${ this . endpoint }/add-student` ; return this . http . post ( API_URL , data ) . pipe ( catchError ( this . errorMgmt ) ) ; } GetStudents ( ) { return this . http . get ( `${ this . endpoint }` ) ; } GetStudent ( id ) { let API_URL = `${ this . endpoint }/read-student/${ id }` ; return this . http . get ( API_URL , { headers : this . headers } ) . pipe ( map ( ( res ) => { return res || { } ; } ) , catchError ( this . errorMgmt ) ) ; } UpdateStudent ( id , data ) { let API_URL = `${ this . endpoint }/update-student/${ id }` ; return this . http . put ( API_URL , data , { headers : this . headers } ) . pipe ( catchError ( this . errorMgmt ) ) ; } DeleteStudent ( id ) { var API_URL = `${ this . endpoint }/delete-student/${ id }` ; return this . http . delete ( API_URL ) . pipe ( catchError ( this . errorMgmt ) ) ; } errorMgmt ( error ) { let errorMessage = '' ; if ( error . error instanceof ErrorEvent ) { errorMessage = error . error . message ; } else { errorMessage = `Error Code: ${ error . status }\nMessage: ${ error . message }` ; } console . log ( errorMessage ) ; return throwError ( errorMessage ) ; } }