Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!