Sleeping with Typescript

Asked

Viewed 33 times

0

Good afternoon, I am in need of making the typescript excute a call every 10 milliseconds. I gave a search using setInterval but the information comes as Undefined but when I save, the values in this.tags.name comes as Undefined.

export class InicialComponent implements OnInit {

  tagsMongoUrl = 'http://localhost:8080/tags';
  tags = [];
  tagsSave = new Tags();
  msgs: Message[] = [];
  nome = '';
  valor = '';

  constructor(private principalService: PrincipalService, private http: Http) { }

  ngOnInit() {
    this.pesquisar();
  }

  pesquisar() {
    this.principalService.pesquisar()
      .then(() => null);
  }

  salvar() {

    setInterval(function () {
      const v = 100;

      for (let i = 0; i < v; i++) {
        this.tagsSave.name = 'name ' + i;//undefined aqui pois não acessa o objeto
        this.tagsSave.value = i.toString();
        this.nome = this.tagsSave.name;
        this.valor = this.tagsSave.value;
        console.log(this.valor);

        this.saveData();
      }
    }, 3000);
  }


  saveData() {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post(this.tagsMongoUrl,
      JSON.stringify(this.tagsSave), { headers })
      .toPromise()
      .then(response => response.json());
  }

}

1 answer

0


The problem is that when you use the setInterval, passes an anonymous function, and within Anonimas functions the scope changes, and the this refers to the anonymous function, not to the method of its class.

To solve this you have three options:

  1. Arrow Function.

salvar() {

  setInterval(() => {
    const v = 100;

    for (let i = 0; i < v; i++) {
      this.tagsSave.name = 'name ' + i; //undefined aqui pois não acessa o objeto
      this.tagsSave.value = i.toString();
      this.nome = this.tagsSave.name;
      this.valor = this.tagsSave.value;
      console.log(this.valor);

      this.saveData();
    }
  }, 3000);
}

Explanation: Arrow functions have no scope, so the this continues to refer to the external scope of the function.

  1. Variable referring to this created in the top function.

salvar() {
  let $that = this;
  setInterval(function() {
    const v = 100;

    for (let i = 0; i < v; i++) {
      $that.tagsSave.name = 'name ' + i; //undefined aqui pois não acessa o objeto
      $that.tagsSave.value = i.toString();
      $that.nome = $that.tagsSave.name;
      $that.valor = $that.tagsSave.value;
      console.log($that.valor);

      $that.saveData();
    }
  }, 3000);
}

Explanation: the anonymous function can access the variable $that, which is a reference to this of the external function.

  1. Use the bind in anonymous function.

salvar() {

  setInterval(function() {
    const v = 100;

    for (let i = 0; i < v; i++) {
      this.tagsSave.name = 'name ' + i; //undefined aqui pois não acessa o objeto
      this.tagsSave.value = i.toString();
      this.nome = this.tagsSave.name;
      this.valor = this.tagsSave.value;
      console.log(this.valor);

      this.saveData();
    }
  }.bind(this), //<-- aqui
  3000);
}

Explanation: the first argument of the method bind informs the function what the variable this will represent in its context.


The most modern and correct option would be the second, with Arrow functions. I recommend using it.

Browser other questions tagged

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