我试图在Firebase中的值事件侦听器中设置在类内声明为公共的变量。虽然,我收到错误
Uncaught TypeError: Cannot read property 'driverAssigned' of null.
如何在此Firebase侦听器中设置公共变量?
我已经尝试在类中创建一个回调函数来设置我的变量,但是错误是相同的。
export class InRideComponent implements OnInit {
public driverAssigned: boolean;
constructor(
private fireb: AngularFireDatabase
) {
const driverRef_str = "/queue/user";
this.fireb.database.ref(driverRef_str).on('value', function(snapshot) {
if (snapshot.val() !== null) {
console.log("A driver has been assigned!");
this.driverAssigned = true;
}
})
}
}
答案 0 :(得分:0)
这更多是Javascript / Typescript上下文问题:
尽管,我没有对此进行检查,但您可能想在下面尝试一下:
this.fireb.database.ref(driverRef_str).on('value', function(snapshot) {
if (snapshot.val() !== null) {
console.log("A driver has been assigned!");
this.driverAssigned = true;
}
}.bind(this));
如果不起作用,请告诉我:)