I really导入的第 3 方脚本来触发类似的功能show_end_screen
(below)
我的组件
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到导入的脚本。当第 3 方脚本运行时show_end_screen(data)
我成功登录data
到控制台。但我无权访问this
或任何其他对角度的引用
this.router.navigate(['play']);
ERROR TypeError: Cannot read property 'nav' of undefined
当您将类绑定方法作为值传递时,它会丢失上下文(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']);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)