【问题标题】:angular - access array which is outside of ngOnInit()angular - 访问 ngOnInit() 之外的数组
【发布时间】:2018-03-23 10:49:44
【问题描述】:

中有一个叫做numbers的数组
export class MyphotographsComponent implements OnInit { 
  numbers =[]
}

在“数字”数组之后我有 onNgInit(){}。在这有一个功能。通过这个函数,我想将一个变量推送到 NgOnInit 之外的数组中。我尝试了 'this.numbers.push[i]' 这很有效。在这方面需要一些帮助。

下面是我的示例代码

 export class MyphotographsComponent implements OnInit {

 numbers= [];

 ngOnInit() {

    function loadImages() {
      this.numbers.push[1]
    }

    loadImages();
  }

}

【问题讨论】:

    标签: javascript angular angular-directive


    【解决方案1】:

    this 的上下文方面似乎存在问题。尝试将loadImages 函数放在ngOnInit 之外:

    export class MyphotographsComponent implements OnInit {
    
        numbers= [];
    
        ngOnInit() {
            this.loadImages();
        }
    
        private loadImages() {
            this.numbers.push[1]
        }
    
    }
    

    或者把loadImages写成箭头函数:

    export class MyphotographsComponent implements OnInit {
    
        numbers= [];
    
        ngOnInit() {
            const loadImages = () => this.numbers.push[1];
            loadImages();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-27
      • 2021-06-07
      • 1970-01-01
      • 2018-07-04
      • 2021-05-13
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多