angular 5:将回调方法传递给带有angular的第三方脚本 [英] angular 5: pass a callback method to 3rd party script with angular

查看:79
本文介绍了angular 5:将回调方法传递给带有angular的第三方脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

真的导入的第三方脚本来触发类似show_end_screen(如下)的功能

I really an imported 3rd party script to trigger a function like 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或任何其他有关angular

init_game(this.show_end_screen) <== Here I am passing show_end_screen to the imported script. when the 3rd party script runs show_end_screen(data) I successfully log data to the console. But i dont have access to this or any other reference to angular

this.router.navigate(['play']);< ==在这里,我收到控制台错误

this.router.navigate(['play']); <== here i get a console error

ERROR TypeError: Cannot read property 'nav' of undefined

推荐答案

当您将类绑定方法作为值传递时,它将丢失上下文(this).您可以显式绑定或在回调中调用:

When you pass a class-bound method as a value it loses the context (this). You can bind explicitly or call within the callback:

ngOnInit() {
  // explicit binding
  init_game(this.show_end_screen.bind(this));

  // lexical binding
  init_game(data => this.show_end_screen(data));
}

您也可以对组件使用实例绑定方法.

You can also use an instance-bound method for your component instead.

show_end_screen = (data) => {
  this.router.navigate(['play']);
}

这篇关于angular 5:将回调方法传递给带有angular的第三方脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆