I'm trying to understand what is gong on here and why I'm getting an error if I call a function a certain way and not getting the error when i call the function a different way. Here is the way that produces the error first:
player.service.ts file
in the @Injectable
i have
private roomsRef: Firebase;
constructor() {
this.roomsRef = new Firebase("https://xxx.firebaseio.com/rooms");
}
postGameActions(roomId: string) {
console.log("post game actions start on " + roomId);
//error on below 'this'
this.roomsRef.child(roomId).child("board").once("value", snap => {
let board = snap.val();
//do stuff with 'board' object
});
}
room.component.ts file
activateTimer(roomId: string, roomName: string, callback) {
var timer = setInterval(redirectTimer, 1000);
var seconds: number = 5;
var timerHtml = document.getElementById("divRedirectTimer" + roomName);
timerHtml.innerHTML = "[" + seconds + "]";
function redirectTimer() {
timerHtml.innerHTML = "[" + (seconds--) + "]";
if(seconds === 0) {
clearInterval(timer);
callback(roomId);
}
};
}
call non-working version like this
activateTimer(room.id, room.name, _playerService.postGameActions)
Error:
EXCEPTION: TypeError: this is undefined
Working version
Works fine when like this but no use of setInterval()
since activateTimer
just calls the service method
room.component.ts file
activateTimer(roomId: string, roomName: string) {
var timer = setInterval(redirectTimer, 1000);
var seconds: number = 5;
var timerHtml = document.getElementById("divRedirectTimer" + roomName);
timerHtml.innerHTML = "[" + seconds + "]";
function redirectTimer() {
timerHtml.innerHTML = "[" + (seconds--) + "]";
if(seconds === 0) {
clearInterval(timer);
}
}
this._playerService.postGameActions(roomId);
call working version like this
activateTimer(room.id, room.name)
Why is the 'this' undefined when i call postGameActions
as a callback? I'm sure I'm missing something simple here
You need to wrap the call into an arrow function:
activateTimer(room.id, room.name, () => {
_playerService.postGameActions();
});
The problem in your code is that you reference directly a function so you lose the object it will be executed on.
Another way would be to use the bind method:
activateTimer(room.id, room.name, _playerService.postGameActions.bind(_playerService);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With