2

I need a short delay before a server gets called. I tried using setTimeout:

setTimeout(this.callServer, 1000);

And in the function:

callServer(){
  this._item.someVar = "changed";
  this._service.deleteItem(this._item)
      .subscribe(response => this.onDeleted(response),
        error => this.handleError(error));
}

The function gets called but this causes an error:

TypeError: Cannot read property 'someVar' of undefined

And when i log "this" in the console it outputs undefined.

How can I access class methods and member variables after a delay? Is there a better method or some functionality I need to activate first?

Björn Kechel
  • 7,933
  • 3
  • 54
  • 57
  • This is answered in the TypeScript FAQ; see https://github.com/Microsoft/TypeScript/wiki/FAQ#why-does-this-get-orphaned-in-my-instance-methods – Ryan Cavanaugh Feb 16 '16 at 16:23
  • 1
    `setTimeout(this.callServer.bind(this), 1000);` – dfsq Feb 16 '16 at 16:32
  • thanks @dfsq, this worked, if you want to post the answer, i will accept it – Björn Kechel Feb 16 '16 at 16:49
  • @RyanCavanaugh should it not only be a duplicate if it has an answer on stackoverflow? – Björn Kechel Feb 16 '16 at 16:52
  • @RyanCavanaugh And can you please post a link to the original question. I can't find the question on your github link, and neither the solution that dsfq posted in the comments. The other stackoverflow question does not address setTimeout and uses a different solution – Björn Kechel Feb 16 '16 at 16:58
  • The fundamental problem is the same -- passing a naked `classRef.methodName` reference to something that takes a callback. If you think this isn't a duplicate, you haven't understood the other answer and should ask a new question about why you think these are different situations. – Ryan Cavanaugh Feb 16 '16 at 17:41
  • 1
    You could use arrow functions to avoid this behavior... – Thierry Templier Feb 16 '16 at 17:46

0 Answers0