horse.service.ts 2.41 KB
Newer Older
1 2
import { Injectable } from '@angular/core';
import { Horse } from '../dto/horse';
3
import { HttpClient, HttpParams } from '@angular/common/http';
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
import { Globals } from '../global/globals';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class HorseService {
  private messageBaseUri: string = this.globals.backendUri + '/horses';

  constructor(private httpClient: HttpClient, private globals: Globals) {
  }

  /**
   * Loads specific horse from the backend
   * @param id of horse to load
   */
  getHorseById(id: number): Observable<Horse> {
    console.log('Load horse details for ' + id);
    return this.httpClient.get<Horse>(this.messageBaseUri + '/' + id);
  }

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
  /**
   * Loads all horses from the backend
   */
  getAllHorses(): Observable<Array<Horse>> {
    console.log('Load all horses');
    return this.httpClient.get<Array<Horse>>(this.messageBaseUri);
  }

  /**
   * Load all horses from the backend that correspond to a filter
   * @param filter to use
   */
  getFilteredHorses(filter: HttpParams): Observable<Array<Horse>> {
    console.log('Load all filtered horses');
    return this.httpClient.get<Array<Horse>>(this.messageBaseUri, { params: filter });
  }

42 43 44 45 46
  /**
   * Adds a specific horse to the backend and loads it if successful
   * @param horse
   */
  addHorse(horse: Horse): Observable<Horse> {
47
    console.log('Add new horse ' + JSON.stringify(horse));
48 49
    return this.httpClient.post<Horse>(this.messageBaseUri, horse);
  }
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
50

51 52 53 54
  /**
   * Update a specific horse with the supplied values
   * @param horse
   */
55 56 57 58 59
  updateHorse(horse: Horse): Observable<Horse> {
    console.log('Update horse with id ' + horse.id + ': '+ JSON.stringify(horse));
    return this.httpClient.put<Horse>(this.messageBaseUri + '/' + horse.id, horse);
  }

Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
60
  /**
61 62 63 64 65 66 67 68 69 70 71 72
   * Delete a horse from the backend
   * @param id
   */
  deleteHorse(id: number): Observable<Object> {
    console.log('Delete horse with id ' + id);
    return this.httpClient.delete(this.messageBaseUri + '/' + id);
  }

  /**
   * Uploads a file to the remote server
   * @param fileToUpload
   * @param newFileName
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
73 74 75 76 77 78 79 80 81 82
   */
  postFile(fileToUpload: File, newFileName: string): Observable<Object> {
    // Prepare the form
    var formData: FormData = new FormData();
    formData.append('file', fileToUpload, newFileName);

    // Upload the image and return the result
    return this.httpClient
      .post(this.messageBaseUri + '/upload', formData);
  }
83
}