0

He estado mirando este tutorial: https://www.javatpoint.com/angular-spring-crud-example, pero no he encontrado forma de cubrir valores select al realizar una petición de una API REST.

Os comparto los siguientes códigos fuente:

add-employee.component.html

   <div class="form-group">
          <label for="department">{{'employeeDepartment' | translate }}</label>
          <select class="form-control" formControlName="employee_department" data-toggle="tooltip"
                  data-placement="right" title="{{'employeeDepartment' | translate }}">
            <option value="null">{{'SelectDepartment' | translate }}</option>
            <option value="B-Tech">B-Tech</option>
            <option value="BCA">BCA</option>
            <option value="MCA">MCA</option>
            <option value="M-Tech">M-Tech</option>
          </select>
          <span *ngIf=" employeeDepartment.errors.required">{{'ErrorEmployeeDepartment' | translate }}</span>
        </div>

        <div class="form-group">
          <label for="location">{{'employeeLocation' | translate }}</label>
          <select class="form-control" formControlName="employee_location" data-toggle="tooltip"
                  data-placement="right" title="{{'employeeLocation' | translate }}">
            <option value="null">{{'SelectLocation' | translate }}</option>
            <option value="B-Tech">B-Tech</option>
            <option value="BCA">BCA</option>
            <option value="MCA">MCA</option>
            <option value="M-Tech">M-Tech</option>
          </select>
          <span *ngIf=" employeeDepartment.errors.required">{{'ErrorEmployeeLocation' | translate }}</span>
        </div>

add-employee.component.ts

import { Component, OnInit } from "@angular/core";
import {HttpClientService, Employee, Department, Location, ItemSet, Item} from '../service/httpclient.service';
import { Router } from '@angular/router';
import {FormControl,FormGroup,Validators} from '@angular/forms';

@Component({
  selector: "app-add-employee",
  templateUrl: "./add-employee.component.html",
  styleUrls: ["./add-employee.component.css"]
})
export class AddEmployeeComponent implements OnInit {
  employee: Employee = new Employee();
  showSpinner: any;

  constructor(private httpClientService: HttpClientService,
    private router: Router) {}

  employee: Employee = new Employee();
  submitted = false;

  ngOnInit() {
    this.submitted = false;
  }

  employeesaveform = new FormGroup({
    employee_name:new FormControl('' , [Validators.required , Validators.minLength(10) ] ),
    employee_last:new FormControl('' , [Validators.required , Validators.minLength(10) ] ),
    employee_nif:new FormControl('' , [Validators.required , Validators.minLength(9) ] ),
    employee_department: new FormControl('' , Validators.required),
    employee_location: new FormControl('' , Validators.required),
    employee_chief: new FormControl(),
    employee_itemset: new FormControl(),
    employee_item: new FormControl(),
    employee_registerdate: new FormControl(),
    employee_shutdate: new FormControl()
  });

  saveEmployee(saveEmployee){
    this.employee = new Employee();
    this.employee.employeeName = this.employeeName.value;
    this.employee.employeeLastNames = this.employeeLastNames.value;
    this.employee.employeeNIF = this.employeeNIF.value;
    this.employee.department.departmentId = this.employeeDepartment.value;
    this.employee.location.locationId = this.employeeLocation.value;
    this.employee.employeeChief.employeeId = this.employeeChief.value;
    this.employee.itemSet.itemSetId = this.employeeItemSet.value;
    this.employee.item.itemId = this.employeeItem.value;
    this.employee.employeeRegisterDate = this.employeeRegisterDate.value;
    this.employee.employeeShutDate = this.employeeShutDate.value;

    this.submitted = true;
    this.createEmployee();
  }

  get employeeName(){
    return this.employeesaveform.get('employee_name');
  }

  get employeeLastNames(){
    return this.employeesaveform.get('employee_last');
  }

  get employeeNIF(){
    return this.employeesaveform.get('employee_nif');
  }

  get employeeDepartment(){
    return this.employeesaveform.get('employee_department');
  }

  get employeeLocation(){
    return this.employeesaveform.get('employee_location');
  }

  get employeeChief(){
    return this.employeesaveform.get('employee_chief');
  }

  get employeeItemSet(){
    return this.employeesaveform.get('employee_itemset');
  }

  get employeeItem(){
    return this.employeesaveform.get('employee_item');
  }

  get employeeRegisterDate(){
    return this.employeesaveform.get('employee_registerdate');
  }

  get employeeShutDate(){
    return this.employeesaveform.get('employee_shutdate');
  }


  addEmployeeForm(){
    this.submitted=false;
    this.employeesaveform.reset();
  }

  createEmployee(): void {
    console.debug(this.employee);
    this.httpClientService.createEmployee(this.employee).subscribe(data => {
      alert("Employee created successfully.");
      this.router.navigate([''])
    });
  }
}

httpclient.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

export class Department {
  constructor(
    public departmentId: string,
    public departmentName: string,
    public headquarters: Headquarters
  ) {}
}

export class Location {
    public locationId: number;
    public department: Department;
    public locationAbbreviation: string;
    public locationDescription: string;
}

@Injectable({
  providedIn: 'root'
})
export class HttpClientService {
  constructor(private httpClient: HttpClient) {}

  getDepartments() {
    return this.httpClient.get<Department[]>('http://localhost:9898/xxxxxx/v1/departmentmanage/departments');
  }

  public deleteDepartment(department) {
    return this.httpClient.delete<Department>(
      'http://localhost:9898/xxxxxx/v1/departmentmanage/department' + '/' + department.departmentId
    );
  }

  public createDepartment(department) {
    return this.httpClient.post<Department>(
      'http://localhost:9898/xxxxxx/v1/departmentmanage/department',
      department
    );
  }

  public updateDepartment(department) {
    return this.httpClient.put<Department>(
      'http://localhost:9898/xxxxxx/v1/departmentmanage/departments' + '/' + department.departmentId,
      department
    );
  }

  getLocations() {
    return this.httpClient.get<Location[]>('http://localhost:9898/xxxxxx/v1/locationmanage/locations');
  }

  public deleteLocation(location) {
    return this.httpClient.delete<Location>(
      'http://localhost:9898/xxxxxx/v1/locationmanage/location' + '/' + location.locationId
    );
  }

  public createLocation(location) {
    return this.httpClient.post<Location>(
      'http://localhost:9898/xxxxxx/v1/locationmanage/location',
      location
    );
  }

  public updateLocation(location) {
    return this.httpClient.put<Location>(
      'http://localhost:9898/xxxxxx/v1/locationmanage/locations' + '/' + location.locationId,
      location
    );
  }

Otras preguntas similares: https://stackoverflow.com/questions/43042481/angular2-how-to-get-data-using-query-params-from-dropdown-selection, https://stackoverflow.com/questions/27982320/fill-select-element-using-angular-based-on-query-string-parameter, https://stackoverflow.com/questions/38950494/how-to-show-table-information-with-select-option-in-angular

El objetivo es que en el formulario de añadir salga un despegable con todos los valores extraídos del GET, para así cubrir las FKs obligatorias de la BD de MySQL.

Alguna solución, tanto para HTML como para el archivo ts, por favor?

Muchas gracias! :)

1 respuesta 1

0

Por lo que entiendo, quieres que las opciones del selector, sean 'pobladas' por los datos de tienes en, por ejemplo una arreglo que extraes de una petición... ¿Has probado con la directiva NgFor, donde estableces las opciones en el html ?

   <div *ngFor="let departamento of this.departamentos">
      <option value="{{departamento.id}}">
         {{departamento.nombre}}
      </option>
   </div>
4
  • 2
    Debería usar la directiva en el option, el div ahí no tiene sentido. Recomiendo usar ngValue en lugar de value el 26 nov. 2020 a las 11:29
  • Muy buenas de nuevo. Lo del HTML, lo comprendo. Y que me decís en modo TypeScript? En el sentido de iniciarlos por defecto o mediante funciones, ahí no doy llegado a implementar.
    – user39427
    el 26 nov. 2020 a las 11:40
  • 1
    En el constructor, por ejemplo, te suscribes al servicio getDepartamentos y guardas los datos que te proporcione en un arreglo... Tambien sería recomendable que añadieras una directiva *NgIf="!this.departamentos" antes del NgFor para evitar problemas por el retardo de adquisición de datos... el 26 nov. 2020 a las 12:31
  • @VicenteSanchez De acuerdo, lo haré de esa forma. Muchas gracias. :)
    – user39427
    el 26 nov. 2020 a las 14:03

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.