0

I have called a method in setTimeout() which in turn calls an HTTP service in Angular.

But when the service method is being called I'm getting the following error: Cannot read properties of undefined (reading '<getUsernamesWithPattern>')

The newFunc() is called on keyup event.

 newFunc() {

    clearTimeout(this.typingTimer);
    if (this.myInput)  //checking if input value has some data and it's not empty
    {
      this.typingTimer = setTimeout(this.doneTyping, this.doneTypingInterval);
    }
  }

This method is being called inside of setTimeout:

 doneTyping() {
    //do something
    console.log("testing method" + this.myInput.value)
    let pattern = this.myInput.value;
    console.log(pattern);
    this.friendsListService.getUsernamesWithPattern(pattern).subscribe(data => {
      console.log(data);
    });
  }

What am I missing here? Since setTimeout is an asynchronous function it should be able to call service but it's not able to call the service.

Note: I have declared initialized the friendsListService in the constructor.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Does this answer your question? [How to access the correct \`this\` inside a callback](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – jonrsharpe Jul 23 '23 at 14:25
  • this explains regarding `this` keyword. I think I'm using it correctly because I'm able to log the `pattern` in `doneTyping()` but not able to call the Service's method. – UltraLegend Jul 23 '23 at 14:39

1 Answers1

0

Look at this keyword inside the doneTyping method when it is called by setTimeout.

The context of this changes, and it no longer refers to the component instance.

Try:

newFunc() {
  clearTimeout(this.typingTimer);
  if (this.myInput) {
    this.typingTimer = setTimeout(() => {
      this.doneTyping();
    }, this.doneTypingInterval);
  }
}

doneTyping() {
  console.log("testing method" + this.myInput.value);
  let pattern = this.myInput.value;
  console.log(pattern);
  this.friendsListService.getUsernamesWithPattern(pattern).subscribe(data => {
    console.log(data);
  });
}

Andrew Arrow
  • 4,248
  • 9
  • 53
  • 80
  • this does not work. this is like implementing doneTyping() method inside the setTimeout() where I cannot access this.myInput.value – UltraLegend Jul 23 '23 at 14:32
  • ok i edited code with small changes – Andrew Arrow Jul 23 '23 at 14:35
  • with this change i dont know why, but i'm getting `undefined` for `this.myInput.value`. – UltraLegend Jul 23 '23 at 16:14
  • Got it man, it should be just `this.myInput`. This approach worked and explanation for this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#using_arrow_functions – UltraLegend Jul 23 '23 at 16:27