Callback generates “TypeError: this is undefined” in Angular2/Firebase

天涯浪子 提交于 2021-02-09 02:45:31

问题


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


回答1:


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);


来源:https://stackoverflow.com/questions/36815028/callback-generates-typeerror-this-is-undefined-in-angular2-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!