[英]Angular 2 - Code is not correctly executed in callback (3rd party lib)
[英]angular 5: pass a callback method to 3rd party script with angular
我真的是一個導入的第三方腳本來觸發像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
當您將類綁定方法作為值傳遞時,它會丟失上下文( 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']);
}
這是因為this
指的是調用上下文,而不是指定回調的上下文。 你應該能夠完成這項工作,通過明確界定哪些情況下this
指的是通過使用bind
功能。
所以你的代碼看起來像這樣:
ngOnInit() {
init_game(this.show_end_screen.bind(this))
}
我假設this.router
是在你的構造函數中定義的
除了@Explossion Pills答案之外,您還可以將方法定義為屬性並保存bind()
調用
show_end_screen = (data) => {
console.log(data) //this works
this.router.navigate(['play']); //"this" is undefined
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.