Delete a record from a table and this is automatically removed in Angular

3

I would like to know how I can do when I delete a record from a table that is automatically removed from that table, since when I delete I always have to reload the page to no longer see the record deleted in the table.

My code ts:

import { Component, OnInit } from '@angular/core';
import {ArtistaserviceService} from './../../services/artistaservice.service';

@Component({
  selector: 'app-artista',
  templateUrl: './artista.component.html',
  styles: []
})
export class ArtistaComponent implements OnInit{
  
  artistas:any[] = [];

  constructor(private artistaS:ArtistaserviceService) {
    
   }

  ngOnInit(){
     this.artistaS.getArtistas()
     .subscribe(data =>{
       this.artistas = data;
       console.log(this.artistas);
     })
  }

  borrarArtista(id:string){
    this.artistaS.borrarArtista(id)
    .subscribe(
      respuesta => {
        if(respuesta){
          console.log(respuesta);
          
        }
        else{
          delete this.artistas[id];
         

        }
      }
    )
    
  }

 
}

My HTML:

                <tr *ngFor="let art of artistas; let i = index">
                    <td>{{i+1}}</td>



                    <td>{{art.nombreartista}}</td>
                    <td>{{art.anonacimiento}}</td>
                    <td>{{art.descripcion1}}</td>
                    <td class="text-rigth w120">

                        <button [routerLink]="['/arts', art.idartista]" type="submit" class="btn btn-outline-success">
          Editar
          </button>

                        <button type="submit" (click)="borrarArtista(art.idartista)" class="btn btn-outline-danger">
          Eliminar
          </button>
                    </td>
                </tr>

            </tbody>
    
asked by Alex 05.12.2018 в 04:09
source

2 answers

1

The delete operator does not remove elements from an array, just leave undefined in that position:

let array=[1,2,3,4]

delete array[2];

console.log(array);
console.log(array.length);

Use splice to remove:

let array=[1,2,3,4];
array.splice(2,1); //desde la posición 2, eliminamos 1 elemento
console.log(array);
    
answered by 05.12.2018 в 10:37
0

I would recommend that the code you have in the ngOnInit() remove it and write it in a normal method of the class, like this:

ngOnInit(){
   getArtistas();
}

getArtistas(){
   this.artistaS.getArtistas()
      .subscribe(data =>{
         this.artistas = data;
      console.log(this.artistas);
   })
}

Doing this, when you execute the method of deleteArtist () within the conditional you have put the method getArtists () , like this:

if(respuesta){
   console.log(respuesta);
   getArtistas()     
}

doing the above, you update the information you are showing

    
answered by 05.12.2018 в 14:30