horse.component.ts 2.2 KB
Newer Older
1 2 3
import { Component, OnInit } from '@angular/core';
import { HorseService } from '../../service/horse.service';
import { Horse } from '../../dto/horse';
4
import { ActivatedRoute } from '@angular/router';
5 6
import { OwnerService } from 'src/app/service/owner.service';
import { Owner } from 'src/app/dto/owner';
7 8 9 10 11 12 13 14 15 16 17

@Component({
  selector: 'app-horse',
  templateUrl: './horse.component.html',
  styleUrls: ['./horse.component.scss']
})
export class HorseComponent implements OnInit {

  error = false;
  errorMessage = '';
  horse: Horse;
18
  ownerName: string;
19

20
  constructor(private horseService: HorseService, private route: ActivatedRoute, private ownerService: OwnerService) { }
21 22

  ngOnInit(): void {
23 24 25
    // Extract id from url
    const horseId: string = this.route.snapshot.paramMap.get('id');
    this.loadHorse(parseInt(horseId));
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
  }

  /**
   * Error flag will be deactivated, which clears the error message
   */
  vanishError() {
    this.error = false;
  }

  /**
   * Loads the horse for the specified id
   * @param id the id of the horse
   */
  private loadHorse(id: number) {
    this.horseService.getHorseById(id).subscribe(
      (horse: Horse) => {
        this.horse = horse;
43
        this.loadOwnerNameForHorse(horse.owner);
44 45 46 47 48 49 50
      },
      error => {
        this.defaultServiceErrorHandling(error);
      }
    );
  }

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
  /**
   * Loads the name of the owner of a horse
   * @param id of the owner to get
   */
  private loadOwnerNameForHorse(id: number) {
    this.ownerService.getOwnerById(id).subscribe(
      (owner: Owner) => {
        console.log(owner.name)
        this.ownerName = owner.name;
        console.log(this.ownerName);
      },
      error => {
        this.ownerName = "N/A";
      }
    )
  }

68 69 70 71 72 73 74 75 76 77 78 79 80 81
  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;
    }
  }
}