Cytoscape.js 和 Angular 5 - 不可能在 cytoscape 范围之外使用变量

Cytoscape.js and Angular 5 - not possible to use variables outside cytoscape scope

早上好,我想在单击图形的任何节点后设置 'test' 变量的值,但不幸的是我的变量在事件函数中未定义。是否有可能获得 'test' 功能。 这是我的部分代码:

export class MainComponent implements OnInit { 
   public test: string = '';
   constructor() {}
   ngOnInit() {
     this.cy = cytoscape({
        container: document.getElementById('cy'),
        layout: this.initializeLayout(),
        style: this.initializeStyles()
     });
     this.cy.on('click', 'node', function (evt) {
        this.test = evt.target.id();
     });
   }

}

您只需更改代码即可使用箭头函数。见下文。

export class MainComponent implements OnInit { 
  public test: string = '';
  constructor() {}
  ngOnInit() {
    this.cy = cytoscape({
       container: document.getElementById('cy'),
       layout: this.initializeLayout(),
       style: this.initializeStyles()
    });
    this.cy.on('click', 'node', (evt) => { // <- CHANGE HERE
       this.test = evt.target.id();
    });
  }
}

使用 function 关键字更改作用域,因此不会起作用。