TypeScript / Angular2 - EXCEPTION:TypeError:无法读取属性' push'未定义的

时间:2016-02-15 14:42:35

标签: typescript angular

我继续教自己TypeScript和Angular2,我仍然讨厌它,但我必须坚持......无论如何,我有一个组件,它从REST服务加载JSON数据。这个JSON数据非常复杂,所以我希望将其分解并在加载时我希望将一些JSON分配给我定义的某种类型的数组。这是我的类型......我列出了我的用户去过的学校的信息......

    export class UserSchool {

        constructor (
            public schoolId: number,
            public yearRange: string,
            public schoolName: string
        ) {
            this.schoolId = schoolId;
            this.yearRange = yearRange;
            this.schoolName = schoolName;
        }
    }

现在这是我的组件,

import {Component, OnInit} from 'angular2/core';
import {UserData} from '../../services/user-data/UserData';
import {UserSchool} from '../../types/types';
import {Observable} from 'rxjs';

@Component({
    selector: 'profile',
    template: require('app/components/profile/profile.html'),
    providers: [],
    directives: [],
    pipes: []
})

export class Profile implements OnInit {

    userPhotos: any;
    userInfo: any;
    gapageName: string;
    albums: string[];
    userData: any;
    userSchools: UserSchool[];

    constructor(private userData:UserData) {
        this.userSchools = [];
    }

    ngOnInit() {
        // Use forkJoin as we don't need order in the calls
        Observable.forkJoin([
            this.userData.getUserPhotos('123456'),
            this.userData.getUserInfo()]).subscribe(t=> {
            this.userPhotos = t[0];
            this.userInfo = t[1];
            this.gapageName = this.userPhotos.gapageName;

           /*                    
           this.userInfo.data[0].items[0].entries is [Object, Object]
            each item is like so:
            {
            id: 665
            text: "2005 - 2010"
            title: "TownSchool For Bad Children"
            } 
            */
            this.userInfo.data[0].items[0].entries.forEach(function (a) {
                this.userSchools.push(a); // we get problems here...
            });

        });    
    }
}

当我尝试循环使用JSON' this.userInfo.data[0].items[0].entries'从我的Feed中将其推送到数组或类型' UserSchool'我收到一个错误! EXCEPTION: TypeError: Cannot read property 'push' of undefined:我想通过将this.userSchools = [];添加到我的构造函数中可以解决这个问题,但事实并非如此。然后我认为我的范围可能是一个问题,所以在我的forEach我试过:

this.userInfo.data[0].items[0].entries.forEach(function (a) {
    this.parent.userSchools.push(a); // still get an error
});

有人可以告诉我为什么我不能推送到我的对象阵列?非常感谢提前!

1 个答案:

答案 0 :(得分:2)

您应该为forEach方法提供的回调使用箭头函数,以便能够使用词法this

this.userInfo.data[0].items[0].entries.forEach((a) => {
  this.userSchools.push(a); // we get problems here...
});

在您的情况下,this与组件的实例不对应...

有关箭头函数词汇的更多提示,请参阅此链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions