角度4不能推动未定义的数组

时间:2017-08-03 15:02:33

标签: javascript angular

我正在尝试为每个间隔推送一个数组但由于某种原因我得到一个错误,如果我使用ERROR TypeError: Cannot set property 'NaN' of undefined则为this.numbers[this.value] = this.value;,如果我使用core.es5.js:1020 ERROR TypeError: Cannot read property 'push' of undefined则为this.numbers.push(this.value); {1}}

这是我的代码

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-game-control',
  templateUrl: './game-control.component.html',
  styleUrls: ['./game-control.component.css']
})
export class GameControlComponent implements OnInit {
  timer = null;
  value: number;
  interval: number;
  numbers = [];


  constructor() { }


  ngOnInit() {
      console.log(this.numbers);
  }

  onClickStart() {
    console.log('timer called');
    if (this.timer !== null) {
      return;
    }
    this.timer = setInterval(function() {
      this.value += 1;
      // console.log(this.numbers[this.value - 1 ]);
      // this.numbers[this.value] = this.value;
      this.numbers.push(this.value);
      console.log(this.numbers);
    }, this.interval );
  }

  onClickStop() {
    clearInterval(this.timer);
    this.timer = null;
  }

}

我的HTML是

<div class="row">
          <div class="col-xs-12 "> 
            <button type="submit" class="btn btn-success" (click)="onClickStart()">Start</button>
            <button type="button" class="btn btn-danger" (click)="onClickStop()">Stop</button>
            <button type="button" class="btn btn-primary" >Clear</button>
          </div>
</div>
<div class="row">
  <div class="col-xs-10">

  <hr>
  <ul class="list-group">
    <a 
      class="list-group-item" 
      style="cursor: pointer"
      *ngFor="let number of numbers"
      >
      <app-even [num]="number" ></app-even>
      <app-odd [num]="number" ></app-odd> 
    </a>
  </ul>
  </div>
</div>

但我认为这还不重要

1 个答案:

答案 0 :(得分:4)

function () {}导致this不再指向当前的类实例,因为大多数来自其他语言会发生这种情况,请使用箭头函数来获得所需的行为:

this.timer = setInterval(() => {