【问题标题】:Fetching variables & calling functions from different scope in Angular从Angular中的不同范围获取变量和调用函数
【发布时间】:2022-01-17 04:56:54
【问题描述】:

我有一个本地函数,例如,ngOnInit() 中的强制函数(),它由我正在使用的库自动触发。我一定要将它作为 ngOnInit 中的本地函数。

问题 - 我无法访问在该角度组件中声明的变量或调用函数。

    export class MyComponent implements OnInit {
    message= "Hello";
    OuterFunction(){
      console.log("Outer Function called");
    }
    ngOnInit(): void { 
    console.log('msg0: ',this.message);  
    function  compulsoryFunction() {
    console.log('msg: ',this.message);
    this.OuterFunction();
    }

错误如下:

组件中定义的变量或函数是否默认不公开?

提前致谢!

【问题讨论】:

  • 在打字稿中你使用function nameOfFunction(){...},你不能在另一个函数中定义一个函数。是的,由于缺陷,所有变量和函数都是公开的。你用functionName(...){...}this.functionName()来调用它
  • 在打字稿中,我们可以有嵌套函数。这不是限制。
  • 然后使用箭头平面得到“this”

标签: javascript angular typescript angular13


【解决方案1】:

您可以使用arrow functions 更改this 上下文。

export class MyComponent implements OnInit {
  message = 'Hello';

  OuterFunction() {
    console.log('Outer Function called');
  }

  ngOnInit() {
    console.log('msg0: ', this.message);

    const compulsoryFunction = () => {
      console.log('msg: ', this.message);
      this.OuterFunction();
    };
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多