Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

97
Visualizações
Why is this property showing up undefined in angular?

I can't seem to figure out why the first console.log is displaying the parameter correctly but the second shows undefined.

Console Log Output:

text
undefined

Code:

ngOnInit() {
this.getPuzzle();
}
    getPuzzle() {
    this.restProviderService.getPuzzle(this.gameService.getGameId()).subscribe(puzzle => {
      this.puzzleType = puzzle.type;
      this.puzzleValue = puzzle.value;

      console.log(this.puzzleType);

      setTimeout(this.handlePuzzle , 3000);
    });
  }
    
      handlePuzzle() {
          console.log(this.puzzleType);
          if (this.puzzleType == 'text') {
            new Vara("#text", "assets/fonts/vara/Satisfy/SatisfySL.json", [{
              text: 'hello',
              delay: 2000,
              x: 2
            }], {
              fontSize: 25,
              strokeWidth: 1.5,
              duration: 5000,
              color: "black"
            });
          }
        
    
      }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

When you pass the function this.handlePuzzle to setTimeout the this representing your class is lost, and handlePuzzle receives the setTimeout's this instead.

Use an arrow function instead of passing the function itself:

setTimeout(() => this.handlePuzzle(), 3000);
about 4 years ago · Juan Pablo Isaza Relatório

0

Inside JS event listeners this refers to the event target. But inside the handlePuzzle method (sort of an event listener), you need this to refer to the current object instance (as usual in a method).

You have 2 solutions:

  • Use an arrow callback. Arrow callbacks preserve the value of this.

    setTimeout(()=>this.handlePuzzle(), 3000)

    or in your method declaration

    handlePuzzle=()=> { console.log(this.puzzleType);

  • Use bind to set the value of this.

    setTimeout(this.handlePuzzle.bind(this), 3000);

    or, in the constructor

    this.handlePuzzle = this.handlePuzzle.bind(this);

For more details, refer to the following article. https://dev.to/alexdevero/a-quick-guide-to-this-keyword-in-javascript-what-this-is-and-when-7i5

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda