【问题标题】:angular 5: pass a callback method to 3rd party script with angular角度5:将回调方法传递给带有角度的第3方脚本
【发布时间】:2018-03-29 20:45:07
【问题描述】:

真的一个导入的 3rd 方脚本来触发像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 传递给导入的脚本。当第 3 方脚本运行 show_end_screen(data) 时,我成功地将 data 登录到控制台。但我无权访问this 或任何其他对角度的引用

this.router.navigate(['play']);

ERROR TypeError: Cannot read property 'nav' of undefined

【问题讨论】:

标签: angular typescript


【解决方案1】:

当您将类绑定方法作为值传递时,它会丢失上下文 (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']);
}

【讨论】:

  • 很高兴得到您的帮助! .bind(this) ...这会改变回调在其他脚本中的使用方式吗?
  • 我不明白它是如何工作的,但它确实......需要学习......谢谢!
【解决方案2】:

这是因为this 指的是调用上下文,而不是您分配回调的上下文。您应该能够通过使用 bind 函数明确定义 this 所指的上下文来完成这项工作。

所以你的代码应该是这样的:

ngOnInit() {
    init_game(this.show_end_screen.bind(this))
}

【讨论】:

    【解决方案3】:

    我假设 this.router 是在您的构造函数中定义的

    除了@Explossion Pills 答案之外,您还可以将您的方法定义为属性并保存bind() 调用

    show_end_screen = (data) => {
      console.log(data) //this works
      this.router.navigate(['play']); //"this" is undefined
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-21
      • 2016-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多