Angular, list is not updated after an deletion or insertion

Asked

Viewed 297 times

0

I’m developing an application with angular and a api rest in PHP. I am performing a very simple CRUD, just to learn.

My problem is when I will perform an Insert/delete and soon after I will recover a get with all the information. I have a Category management, when saved this category via API it does not appear in my category list, the same appears when I delete, it is not deleted from my category list. but I’m using Postman to keep track of all these requests and they’re made of facts.

I don’t know, it seems like there’s something keeping me from retrieving the updated list.

Example: I have 10 categories so I delete one and still keep displaying 10, even though I access my api to recover the data again. If I have a Reload after about 30 seconds the other category appears

Source code: category-list.component.list // The component that is used to display and delete

ngOnInit() {
    this.getList();
  }

  excluir(desc, id) {

    if (confirm("Deseja excluir a categoria " + desc + " ?")) {
      let index = this.getIndex(id);
      if (index == -1)
        alert('Não foi encontrado o index do código D:');
      else {
        let result = this.categoriaService.delete(id).
          subscribe(dados => { this.getList() },
            (error: any) => alert('erro'));
        //this.items = this.items.splice(index, 1);
        this.items = this.items.filter(item => item.id != id);
      }
    }
  }

  getIndex(id) {
    for (let i = 0; i < this.items.length; i++)
      if (this.items[i].id == id)
        return i;
    return -1;
  }

  getList(page: number = 1) {
    this._compiler.clearCache();
    this.categoriaService.get(page, this.pesquisarValue)
      .subscribe(dados => { console.log(dados); this.exibeLista(dados) }, (error: any) => console.log(error));
  }

  exibeLista(dados) {

    console.log('Total de Itens: ' + dados.result.count);
    this.items = null;

    if (dados.result.count == 0) // Quantidade de itens retornados da consulta
      this.pages = null;
    else {
      if (dados.result.paginas == 0) // Quantidade de paginas
        this.pages = null;
      else {
        this.totalPages = dados.result.paginas;
        this.loadPages();
      }
      this.items = dados.result.item;
    }

    console.log("Quantidade: " + dados.result.count);
  }

Service category.

 insert(ObjJson) {
    /*console.log("Objeto");console.log(ObjJson);console.log("Caminho :"+Auth.url + this.nameClass);console.log("Token :"+Auth.token);*/
    if (ObjJson.id == null)
      return this.http.post(Auth.url + this.nameClass, ObjJson, { headers: { 'token': Auth.token } });
    else
      return this.http.put(Auth.url + this.nameClass + "/" + ObjJson.id, ObjJson, { headers: { 'token': Auth.token } });
  }

  get(page, descricao) {
    page='all';
    return this.http.get(Auth.url + this.nameClass + `?page=${page}&desc=${descricao}`, { headers: { 'token': Auth.token } })
      .pipe(map(response => { return response })) // or try  `response.json()` instead of `response` 
  }

  delete(id) {
    console.log(Auth.url + this.nameClass + "/" + id);
    return this.http
      .delete(Auth.url + this.nameClass + "/" + id, { headers: { 'token': Auth.token } });

  }

Remembering that whenever I run a delete or Insert I check in the database and in Postman and can visualize that it was actually performed, until the get in Postman is right, the problem is when I recover in angular 6.

  • You have to wait for the update or delete return to make the new get call

  • Currently, the best approach to this situation is to use ngrx where your data is in an observable STORE and your components update data through this store. Another way to do it, but I find it very disorganized and subject to bugs, would be to use Behaviorsubject and its components to subscribe to them.

  • @Eduardovargas look like I’m doing in my delete function I just call the update within the subscribe method, and it’s in this method that it returns me if the update or delete was successfully performed

  • @duarbr so the way I did it doesn’t work?

  • It works, but you would need to give another GET after doing an INSERT, UPDATE or DELETE, which would not be very efficient. I recommend that you study Subjects, Behavior Subjects, (REDUX) NGRX.

  • So, that’s the problem, if the way it works, because it’s not cleaning my variable items ... I just created a new project with a single component, a form and below a list of the saved items ... when I save an item I do a get and still I am brought the wrong elements

  • This is the problem, you will have to do REFRESH (via get) in the data (from the API where they were inserted) and also subscribe passing the return to the component ... is not a good practice as the application grows.

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.