簡體   English   中英

angular 5:使用angular將回調方法傳遞給第三方腳本

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM