简体   繁体   English

从另一个 function 从 ngOnInit 访问本地 var

[英]Access local var from ngOnInit from another function

I am new to Angular and TS.我是 Angular 和 TS 的新手。 I am trying to access a local var that is in ngOnInit from outside it, but I don't know how to do it properly.我正在尝试从外部访问 ngOnInit 中的本地 var,但我不知道如何正确执行。 I have a component called BlocklyComponent where I created the var.我有一个名为 BlocklyComponent 的组件,我在其中创建了 var。

    export class BlocklyComponent implements OnInit {
      primaryWorkspace: Blockly.WorkspaceSvg;
      constructor(private sanitizer: DomSanitizer) {
    this.updateXML = this.updateXML.bind(this);
  }
  ngOnInit() {
    var primaryWorkspace = Blockly.inject('primaryDiv',{....} as Blockly.BlocklyOptions);

Inside the NgOnInit function it works correctly, I can see the object without any problem.在 NgOnInit function 内部它工作正常,我可以看到 object 没有任何问题。 However when I add the addchangeListener to read when there is an event I cant access that local var from the new function that is outside ngOnInit.但是,当我添加 addchangeListener 以在发生事件时读取时,我无法从 ngOnInit 外部的新 function 访问该本地变量。

primaryWorkspace.addChangeListener(this.updateXML); //addChangeListener is special for Blockly library
  }
  updateXML(primaryEvent ) 
  {
    if (primaryEvent.isUiEvent) 
     {
       return; //Do not clone ui events 
     };
    var xml = Blockly.Xml.workspaceToDom(primaryWorkspace); //XML machine. Blockly is a library.
    console.log(xml);
  } 

I tried to add this (this.primaryWorkspace) to the call but it takes the property not the local var.我试图将这个(this.primaryWorkspace)添加到调用中,但它使用的是属性而不是本地变量。 I know that is possible to create the function inside ngOnInit and it works but I need to create updateXML outside.我知道可以在 ngOnInit 内部创建 function 并且它可以工作,但我需要在外部创建 updateXML。 Thank you very much非常感谢

Finally, it was a simple problem.最后,这是一个简单的问题。 I solved the issue myself by declaring the var as this.primaryWorkspace instead of declaring it as a VAR.我通过将 var 声明为 this.primaryWorkspace 而不是将其声明为 VAR 自己解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM