2017-08-03 24 views
0

我試圖把陣列上的每一個間隔的陣列上,但由於某種原因,我得到一個錯誤,要麼是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);角4不能推的不確定

這裏是我的代碼

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> 

,但我不認爲它很重要但

回答

4

function() {}導致this不指向當前類實例了,因爲大多數從其他語言所期望的,用箭頭的功能而不是獲得所需的行爲:

this.timer = setInterval(() => { 
+0

我將標誌着一個是正確的幾分鐘任何資源,我可以閱讀這個問題現在得到不同的概率,但解決了我原來的感謝! –

+1

我可能是錯的,但如果答案是正確的,則解釋在語義上是錯誤的。實際上'setInterval'總是從全局範圍運行它的參數,正是他用'function()'來分隔'this'。這將與箭頭函數一起工作,因爲它沒有適當的'this',總是從上下文中扣除它 – Kaddath

+1

可以在那裏找到一些進一步的閱讀:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#As_an_object_method –