add-horse.component.ts 3.45 KB
Newer Older
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
1 2
import { Component, OnInit } from '@angular/core';
import { Horse } from '../../dto/horse';
3
import { Owner } from '../../dto/owner';
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
4
import { HorseService } from '../../service/horse.service';
5
import { OwnerService } from '../../service/owner.service';
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
6 7 8 9 10 11 12 13 14 15

@Component({
  selector: 'app-add-horse',
  templateUrl: './add-horse.component.html',
  styleUrls: ['./add-horse.component.scss']
})
export class AddHorseComponent implements OnInit {
  error = false;
  success: string;
  errorMessage = '';
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
16
  horse: Horse = new Horse(null, null, null, null, null, null, null, null);
17
  owners: Array<Owner>;
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
18
  imageToUpload: File = null;
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
19

20
  constructor(private horseService: HorseService, private ownerService: OwnerService) { }
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
21

22 23 24 25 26 27 28 29 30 31 32
  ngOnInit(): void {
    // Get all owners and save them
    this.ownerService.getAllOwners().subscribe(
      (owners: Array<Owner>) => {
        this.owners = owners;
      },
      error => {
        this.owners = null;
      }
    );
  }
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

  /**
   * Will be called on a click on the success alert close button
   */
  public vanishAlert() {
    this.success = null;
  }

  /**
   * Will be called on a click on the error alert close button
   */
  public vanishError() {
    this.errorMessage = null;
  }

  /**
   * Creates a new horse and loads it
   * @param horse
   */
  public addHorse() {
    console.log("POST horse to API")
    console.log(this.horse);
    this.horseService.addHorse(this.horse).subscribe(
      (result: Horse) => {
        this.success = result.name;
      },
      error => {
        this.defaultServiceErrorHandling(error);
      }
    );
  }

Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
  /**
   * Handles the input on the image input.
   * Inspired from:
   * https://stackoverflow.com/questions/47936183/angular-file-upload
   * @param files
   */
  public handleImageInput(files: FileList) {
    var imageFile: File = files.item(0);

    // Generate a random bytes name to avoid conflicts
    var fileExt: string = imageFile.name.split('.').pop();
    var newFileName: string = this.generateHex(20) + '.' + fileExt;
    this.horse.imagePath = newFileName;

    // Upload the file
    this.uploadFile(imageFile, newFileName)
  }

  /**
   * Uploads the file to the backend with the specified file name
   * @param file
   * @param newFileName
   */
  private uploadFile(file: File, newFileName: string){
    this.horseService.postFile(file, newFileName).subscribe(
      () => {
        console.log("Image successfully uploaded");
      }, error => {
        this.defaultServiceErrorHandling(error)
      });
  }

  /**
   * Generates a random hex with the specified length
   * Inspired from:
   * https://stackoverflow.com/a/27747377
   * @param len
   */
  private generateHex(len: number): string {
    var arr = new Uint8Array((len) / 2)
    window.crypto.getRandomValues(arr)
    return Array.from(arr, this.dec2hex).join('')
  }

  /**
   * Converts a decimal to its hex value
   * @param dec
   */
  private dec2hex(dec: number): string {
    return ('0' + dec.toString(16)).substr(-2)
  }

Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
117 118 119 120 121 122 123 124 125 126 127 128 129 130
  private defaultServiceErrorHandling(error: any) {
    console.log(error);
    this.error = true;
    if (error.status === 0) {
      // If status is 0, the backend is probably down
      this.errorMessage = 'The backend seems not to be reachable';
    } else if (error.error.message === 'No message available') {
      // If no detailed error message is provided, fall back to the simple error name
      this.errorMessage = error.error.error;
    } else {
      this.errorMessage = error.error.message;
    }
  }
}