For*_*ugh 1 javascript firebase firebase-realtime-database angular
ngOnInit() {
console.log('this1: ', this);
this.dbService.chats$.on('value', function(snapshot) {
console.log('this2: ', this);
});
}
Run Code Online (Sandbox Code Playgroud)
第一个 console.log 包含 Component 的所有字段,而第二个控制台日志为null
在匿名函数或回调函数中, this 指的是当前上下文。
所以在你的例子中,它指的是回调函数下的上下文。
所以问题是如何访问 external this。
有两种方法可以访问外部this。
1. 箭头功能:
ngOnInit() {
console.log('this1: ', this);
this.dbService.chats$.on('value', (snapshot) => {
console.log('this2: ', this);
});
}
Run Code Online (Sandbox Code Playgroud)
2. 使用绑定:
ngOnInit() {
console.log('this1: ', this);
this.dbService.chats$.on('value', function(snapshot) {
console.log('this2: ', this);
}.bind(this));
}
Run Code Online (Sandbox Code Playgroud)
使用以下代码:-
ngOnInit() {
console.log('this1: ', this);
this.dbService.chats$.on('value',(snapshot) => {
console.log('this2: ', this);
});
}
Run Code Online (Sandbox Code Playgroud)
这是因为thisnow 指的是function. 但是当您使用粗箭头时,=> this则指的是外部环境。
| 归档时间: |
|
| 查看次数: |
467 次 |
| 最近记录: |