Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback generates "TypeError: this is undefined" in Angular2/Firebase

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

like image 692
ska.dev Avatar asked Apr 23 '16 18:04

ska.dev


1 Answers

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);
like image 128
Thierry Templier Avatar answered Nov 14 '22 22:11

Thierry Templier