回调会生成"TypeError:这是未定义的".在Angular2/Firebase中 [英] 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文件
player.service.ts file
我在 @Injectable
中的
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文件
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)
错误:
EXCEPTION: TypeError: this is undefined
工作版本
在这种情况下工作正常,但不使用 setInterval()
,因为 activateTimer
只是调用服务方法
Works fine when like this but no use of setInterval()
since activateTimer
just calls the service method
room.component.ts文件
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)
当我调用 postGameActions
作为回调时,为什么'this'是未定义的?我确定我这里缺少简单的东西
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.
另一种方法是使用bind方法:
Another way would be to use the bind method:
activateTimer(room.id, room.name, _playerService.postGameActions.bind(_playerService);
这篇关于回调会生成"TypeError:这是未定义的".在Angular2/Firebase中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!