2017-05-28 115 views
-2

我有這樣的一個方法裏面角2無法讀取未定義的屬性「推送」。角2

exportClass AppComponent implements OnInit{ 

private averageList: number [] = number []; 

(...) 

    getAverage(){ 

    this.averageList = []; 
    (....) 
    (....) 

     var source = Observable.forkJoin(
      this.http.get(data2.builds[0].url + this.finalURL), 
      this.http.get(data2.builds[1].url + this.finalURL) 
     ); 

     var subscription = source.subscribe(
      function (x) { 
      let numberOfFails = 0; 
      let count = 0; 
      for(var i = 0; i < x.length; i++){ 
       let data = x[i].json(); 
       contador++; 
       if (data.result === "FAILURE"){ 
       numberOfFails++; 
       } 
      } 
      let average = numberOfFails/count; 
      console.log(numberOfFails + " " + count); 
      console.log(average); 
      this.averageList.push(average); //THIS LINE MAKES AN ERROR 
      }, 
      function (err) { 
      console.log('Error: %s', err); 
      }, 
      function() { 
      console.log('Completed'); 
      }); 
    } 
} 

當我嘗試將元素添加到陣列averageList出現下一個問題:無法讀取的未定義的屬性「推」。 在方法開始時,我使用this.averageList = []清理這個數組。 我該如何解決這個使用數組?謝謝

+0

averageList是如何定義的?在提供的代碼中,我沒有看到它的定義。 –

回答

1

您回撥到source.subscribe是不是一個箭頭功能,所以它的this值不是類,以獲得所需的結果更改source.subscribe使用箭頭函數。找到下面的箭頭功能等效。

var subscription = source.subscribe(
     (x) => { 
     let numberOfFails = 0; 
     let count = 0; 
     for(var i = 0; i < x.length; i++){ 
      let data = x[i].json(); 
      contador++; 
      if (data.result === "FAILURE"){ 
      numberOfFails++; 
      } 
     } 
     let average = numberOfFails/count; 
     console.log(numberOfFails + " " + count); 
     console.log(average); 
     this.averageList.push(average); //THIS LINE MAKES AN ERROR 
     }, 
    (err) => { 
     console.log('Error: %s', err); 
     }, 
    () => { 
     console.log('Completed'); 
     }); 
+0

我該怎麼做?我在這個新的 –

+0

@CarlosY我已經用箭頭函數等效更新了我的答案 – wale

相關問題