我真的导入第三方脚本以触发show_end_screen
(下方)
我的组件
import { Router } from '@angular/router';
import { init_game, start_game, stop_game } from '../../assets/js/game';
@Component({})
export class PlayComponent implements OnInit {
constructor(public router:Router) {}
ngOnInit() {
init_game(this.show_end_screen) // load ready
}
show_end_screen(data){
console.log(data) //this works
this.router.navigate(['play']); //"this" is undefined
}
}
init_game(this.show_end_screen)
< ==这里我将show_end_screen
传递给导入的脚本。当第三方脚本运行show_end_screen(data)
时,我成功将data
记录到控制台。但我无法访问this
或任何其他角度
this.router.navigate(['play']);
< ==这里我收到控制台错误
ERROR TypeError: Cannot read property 'nav' of undefined
答案 0 :(得分:5)
当您将类绑定方法作为值传递时,它会丢失上下文(this
)。您可以显式绑定或在回调中调用:
ngOnInit() {
// explicit binding
init_game(this.show_end_screen.bind(this));
// lexical binding
init_game(data => this.show_end_screen(data));
}
您也可以为组件使用实例绑定方法。
show_end_screen = (data) => {
this.router.navigate(['play']);
}
答案 1 :(得分:0)
这是因为this
指的是调用上下文,而不是指定回调的上下文。您应该能够通过使用this
函数明确定义bind
引用的上下文来完成此工作。
所以你的代码看起来像这样:
ngOnInit() {
init_game(this.show_end_screen.bind(this))
}
答案 2 :(得分:0)
我假设你的构造函数中定义了this.router
除了@Explossion Pills答案,您还可以将方法定义为属性并保存bind()
调用
show_end_screen = (data) => {
console.log(data) //this works
this.router.navigate(['play']); //"this" is undefined
}