无法读取属性'推送'未定义的。 Angular 2

时间:2017-05-28 00:53:26

标签: angular typescript

我在Angular 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中时,会出现下一个问题:无法读取属性&#39; push&#39;未定义的。 在方法的开头,我使用this.averageList = []清理这个数组。 我该如何解决这个问题呢?感谢

1 个答案:

答案 0 :(得分: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');
      });