Repeated data in html (ANGULAR)

Asked

Viewed 134 times

0

I have a *ngFor that fills my html, and this data is fetched from an API, so I use Schedule to reload the data every time it gives seconds = 15.

Only that the data is being placed below the old la in HTML.

HTML:

<p [class]="mainColor + ' teste' " *ngFor="let element of fil">Filial {{ element.FI }} = {{ element.porc }}</p>

TS:

  ngOnInit() {
        schedule.scheduleJob(' 15 * * * * * ', () => {      
          this.MetaService.FiliaisMetaDiarias().subscribe(
  data => {
    const response = (data as any)
    this.objeto_retorno = JSON.parse(response._body);

    this.objeto_retorno.forEach(element => {

      this.tots = element.TOTAL
      element.TOTAL = (element.TOTAL * 100).toFixed(3) + '%'
      element.TOTAL = element.TOTAL.toString().replace(".", ",")
      if (this.tots >= this.MetaAtingida) {

        this.fil.push({
          FI: element.FILIAL,
          porc: element.TOTAL
        });

        this.mainColor = 'MetaAtingida'

      }
        });
    }

Every time the second is = 15 it code is reloaded and put into html, but not by deleting the previous data that is in html.

Somebody knows how to fix this?

  • 1

    The behavior, it seems to me, is due to your this.fil.push() if you are replacing the elements, before you should clean it.

  • I clean the array, but still it remains the same

  • Where you clean?

  • when starting the Schedule function

  • It was better to use the filter and map method than foreach

1 answer

1


See if it works.

ngOnInit() {
        schedule.scheduleJob(' 15 * * * * * ', () => {      
          this.MetaService.FiliaisMetaDiarias().subscribe(
  data => {
    const response = (data as any)
    this.objeto_retorno = JSON.parse(response._body);

    this.fil.length = 0;

    this.objeto_retorno.forEach(element => {

      this.tots = element.TOTAL
      element.TOTAL = (element.TOTAL * 100).toFixed(3) + '%'
      element.TOTAL = element.TOTAL.toString().replace(".", ",")
      if (this.tots >= this.MetaAtingida) {

        this.fil.push({
          FI: element.FILIAL,
          porc: element.TOTAL
        });

        this.mainColor = 'MetaAtingida'

      }
        });
    }

For some very strange reason, in Javascript, you can "reset" an array by setting its size to 0.

var fil = [1,2,3];
//push esvaziar ou redefinir o tamanho.
fil.push(4);
console.log(fil);

//redefinindo o tamanho e fazendo novo push
fil.length = 0;
fil.push(5);

console.log(fil);

Browser other questions tagged

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