update-owner.component.ts 2.08 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 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 65 66 67 68 69 70 71 72 73 74 75 76 77 78
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params} from '@angular/router';
import { Owner } from '../../dto/owner';
import { OwnerService } from '../../service/owner.service';

@Component({
  selector: 'app-update-owner',
  templateUrl: './update-owner.component.html',
  styleUrls: ['./update-owner.component.scss']
})
export class UpdateOwnerComponent implements OnInit {
  error = false;
  success: string;
  errorMessage = '';
  owner: Owner = new Owner(null, null);

  constructor(private ownerService: OwnerService, private route: ActivatedRoute) { }

  ngOnInit(): void {
    // Extract id from url
    const ownerId: string = this.route.snapshot.paramMap.get('id');

    // Get current value of the owner and save it
    this.ownerService.getOwnerById(parseInt(ownerId, 10)).subscribe(
      (owner: Owner) => {
        this.owner = owner;
      },
      error => {
        this.defaultServiceErrorHandling(error);
      }
    );
  }

  /**
   * 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;
  }

  /**
   * Updates a owner and loads it
   * @param owner
   */
  public updateOwner() {
    console.log("PUT owner to API")
    console.log(this.owner);
    this.ownerService.updateOwner(this.owner).subscribe(
      (result: Owner) => {
        this.success = result.name;
      },
      error => {
        this.defaultServiceErrorHandling(error);
      }
    );
  }

  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;
    }
  }
}