import { Injectable } from '@angular/core' ; import { HttpClient } from '@angular/common/http' ; import { Observable } from 'rxjs' ; import { catchError , finalize , map } from 'rxjs/operators' ; import { Speaker } from './speaker.model' ; import { CONFIG } from '../config' ; import { ExceptionService } from '../exception.service' ; import { MessageService } from '../message.service' ; import { SpinnerService } from '../spinner.service' ; const speakersUrl = CONFIG . baseUrls . speakers ; @ Injectable ( { providedIn : 'root' } ) export class SpeakerService { onDbReset = this . messageService . state ; private catchHttpErrors = ( ) => ( source$ ) => source$ . pipe ( catchError ( this . exceptionService . catchBadResponse ) , finalize ( ( ) => this . spinnerService . hide ( ) ) ) ; constructor ( private http , private exceptionService , private messageService , private spinnerService ) { this . messageService . state . subscribe ( state => this . getSpeakers ( ) ) ; } addSpeaker ( speaker ) { this . spinnerService . show ( ) ; return this . http . post < Speaker > ( `${ speakersUrl }` , speaker ) . pipe ( this . catchHttpErrors ( ) ) ; } deleteSpeaker ( speaker ) { this . spinnerService . show ( ) ; return this . http . delete ( `${ speakersUrl }/${ speaker . id }` ) . pipe ( this . catchHttpErrors ( ) ) ; } getSpeakers ( ) { this . spinnerService . show ( ) ; return this . http . get < Speaker [ ] > ( speakersUrl ) . pipe ( map ( speakers => this . sortSpeakers ( speakers ) ) , this . catchHttpErrors ( ) ) ; } sortSpeakers ( speakers ) { return speakers . sort ( ( a , b ) => { if ( a . name < b . name ) { return - 1 ; } if ( a . name > b . name ) { return 1 ; } return 0 ; } ) ; } getSpeaker ( id ) { this . spinnerService . show ( ) ; return this . http . get < Speaker [ ] > ( speakersUrl ) . pipe ( map ( speakers => speakers . find ( speaker => speaker . id === id ) ) , this . catchHttpErrors ( ) ) ; } updateSpeaker ( speaker ) { this . spinnerService . show ( ) ; return this . http . put < Speaker > ( `${ speakersUrl }/${ speaker . id }` , speaker ) . pipe ( this . catchHttpErrors ( ) ) ; } }