Home > Back-end >  I can't fill a table from JSON in angular and there is no error
I can't fill a table from JSON in angular and there is no error

Time:05-18

I am reading through a Query my database, it executes perfectly the query because i can read through the console the JSON is OK but the table does not fill.

This is my component

@Component({
  selector: 'app-envios',
  templateUrl: './envios.component.html',
  styleUrls: ['./envios.component.css']
})
export class EnviosComponent {

  constructor(private conexion: ConexionService) {}
  envios: Envio[];
  @Input() idnum: number




  ngOnInit() {
  }

  buscarEnvio()
  {
    const idnum = parseInt((document.getElementById('idenvio')as HTMLInputElement).value);
    console.log(idnum);
    this.conexion.consultarEnvio(idnum);
  }

}

And this is my conexion service

export class ConexionService {
   envio : Envio[];

  private api = 'http://localhost:8080/ProyectoFinal/webapi';
 consultarEnvio(id: Number)
  {
    const path = `${this.api}/estadoenvio/${id}`;
    return this.http.get<Envio[]>(path).subscribe(envio => {
      console.log(envio);
    });;
  }

}

This is the HTML

<div >
  <div >
    <input type="text"  placeholder="CC" id="idenvio">
    <span >
      <button type="submit"  type="button" (click)="buscarEnvio()">Buscar</button>
    </span>
  </div>
  <br>
  <div  id="tabla">
    <table >
      <thead>
        <tr >
          <th scope="col">Id del envío</th>
          <th scope="col">Nombre del destinatario</th>
          <th scope="col">Dirreción de envío</th>
          <th scope="col">Código Postal</th>
          <th scope="col">Intentos de entrega</th>
          <th scope="col">Estado del envio</th>
        </tr>
      </thead>
      <tbody>
        <tr  *ngFor="let envio of envios">

          <td >{{envio.idEnvio}}</td>
          <td >{{envio.nombreDestinatario}}</td>
          <td >{{envio.direccionCompleta}}</td>
          <td >{{envio.codigoPostal}}</td>
          <td >{{envio.numIntentosEntrega}}</td>
          <td >{{envio.idEstadoEnvio}}</td>
        </tr>
      </tbody>
    </table>


  </div>
</div>

In case you need it, this is the interface

export interface Envio
{
    idEnvio : number;
    nombreDestinatario: string;
    DNINIF: string;
    codigoPostal: string;
    direccionCompleta:string;
    idEstadoEnvio: string;
    numIntentosEntrega: number;

    

}

If I debug I can see the Json is correct JSON OK

CodePudding user response:

You are not assigning any response to envio array. In subscribe(), assign the response to envio

Updated Component:

@Component({
  selector: 'app-envios',
  templateUrl: './envios.component.html',
  styleUrls: ['./envios.component.css']
})
export class EnviosComponent {

  constructor(private conexion: ConexionService) {}
  envios: Envio[];
  @Input() idnum: number

  ngOnInit() {
  }

  buscarEnvio()
  {
    const idnum = parseInt((document.getElementById('idenvio')as HTMLInputElement).value);
    console.log(idnum);
this.conexion.consultarEnvio(idnum).subscribe(data=>{
    this.envios=data;
   }
  }

}

Updated Service:

export class ConexionService {
  private api = 'http://localhost:8080/ProyectoFinal/webapi';
 consultarEnvio(id: Number)
  {
    const path = `${this.api}/estadoenvio/${id}`;
    return this.http.get<Envio[]>(path);
  }
}

CodePudding user response:

The problem is that you are not setting your variable envios which is used to display the data (according to your html).

The method consultarEnvio returns a promise so you need to set your variable in the callback of your async method.

Your code should look like this:

conexionService:

export class ConexionService {
   envio : Envio[];

  private api = 'http://localhost:8080/ProyectoFinal/webapi';
 consultarEnvio(id: Number)
  {
    const path = `${this.api}/estadoenvio/${id}`;
    return this.http.get<Envio[]>(path).then(envio => {
      return envio;
    });
  }

}

Component:

@Component({
  selector: 'app-envios',
  templateUrl: './envios.component.html',
  styleUrls: ['./envios.component.css']
})
export class EnviosComponent {

  constructor(private conexion: ConexionService) {}
  envios: Envio[];
  @Input() idnum: number




  ngOnInit() {
  }

  buscarEnvio()
  {
    const idnum = parseInt((document.getElementById('idenvio')as HTMLInputElement).value);
    console.log(idnum);
    this.conexion.consultarEnvio(idnum).then((envioResult) => {
       this.envios = envioResult;
    });
  }

}
 buscarEnvio()
  {
    const idnum = parseInt((document.getElementById('idenvio')as HTMLInputElement).value);
    console.log(idnum);
    this.conexion.consultarEnvio(idnum).then((envioResult) => {
       this.envios = envioResult;
    });
  }

CodePudding user response:

I see a couple of improvements:

  1. You could use ViewChild to get the element from html, maybe just as a learning purpose for you.
  2. Make the service method return an observable, do not subscribe in service.
  3. Why do you have 'idnum' both as input and also and a const? From what I see, you are trying to read the value of an input element, based on which to trigger the reading from the service. Enforce the field to be numeric, use 2 way binding to set the value of idnum.
  4. When (click)="buscarEnvio()" action is triggered, assign envios$ variable in EnviosComponent ( envios$ = this.conexion.consultarEnvio(idnum) ). 'envios$' will be of type Obervable<Envio[]>. Afterwards, use envios$ in html with async pipe --> *ngFor="let envio of envios$ | async". Could be more pieces of advice, but I think it's something to start with.
  • Related