0

Boa tarde, estou precisando fazer com que o typescript excute um chamada a cada 10 milisegundos. Dei uma pesquisa utilizando setInterval mas as informações vem como undefined porém quando vou salvar, os valores em this.tags.name vem como 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 Resposta 1

0

O problema é que quando você usa o setInterval, passa uma função anônima, e dentro de funçoes anonimas o escopo muda, e o this passa a se referir à função anônima, e não ao método da sua classe.

Para resolver isso você tem três opções:

  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);
}

Explicação: arrow functions não tem escopo, então o this continua se referindo ao escopo externo à função.

  1. Variável referindo ao this criada na função de cima.

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);
}

Explicação: a função anônima pode acessar a variável $that, que é uma referência ao this da função externa.

  1. Usar o bind na função anônima.

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);
}

Explicação: o primeiro argumento do método bind informa à função o que a variável this representará em seu contexto.


A opção mais moderna e correta seria a segunda, com arrow functions. Recomendo utilizá-la.

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .