Angular 5向第三方脚本传回调时this指向异常问题求助
解决Angular组件方法被外部脚本调用时
this指向undefined的问题 这个问题我太熟了——当你把组件的方法作为回调传给外部第三方脚本时,this的上下文会直接丢失,因为外部脚本调用它的时候,并没有绑定到你的PlayComponent实例上。咱们来一步步解决这个问题:
原因分析
你代码里的console.log(data)能正常运行,是因为console是全局对象,哪怕this是undefined,全局的console.log依然能被调用;但this.router.navigate(['play'])报错,是因为此时this已经不是组件实例,自然没有router这个属性。
三种可行的解决方案
1. 用箭头函数包装回调
在ngOnInit里,把回调用箭头函数包裹,箭头函数会自动捕获当前组件的this上下文:
ngOnInit() { init_game((data) => this.show_end_screen(data)) // 箭头函数保留组件的this } show_end_screen(data){ console.log(data) this.router.navigate(['play']); // 现在this指向组件实例了 }
2. 将方法定义为箭头函数
直接把show_end_screen定义成组件的箭头函数属性,这样它的this在定义时就绑定到了组件实例,不管在哪调用都不会变:
export class PlayComponent implements OnInit { constructor(public router:Router) {} // 把方法改成箭头函数属性 show_end_screen = (data) => { console.log(data) this.router.navigate(['play']); } ngOnInit() { init_game(this.show_end_screen) } }
3. 用bind方法绑定this
在传递回调时,用bind(this)手动把方法的this绑定到组件实例:
ngOnInit() { init_game(this.show_end_screen.bind(this)) // 手动绑定this到组件 } show_end_screen(data){ console.log(data) this.router.navigate(['play']); }
这三种方法都能解决你的问题,个人更推荐前两种,尤其是箭头函数的写法,在Angular组件里很常用,能避免很多上下文丢失的坑。
内容的提问来源于stack exchange,提问作者Omar
相关产品推荐
相关产品推荐

