TypeScript/Angular2-异常:TypeError:无法读取属性';推动';未定义的
我继续自学打字和安格拉尔,我仍然讨厌它,但我必须坚持下去。。。无论如何,我有一个组件,它从REST服务加载JSON数据。这个JSON数据非常复杂,所以我希望将其分解,并且在加载时,我希望将一些JSON分配给我定义的特定类型的数组。这是我的类型。。。我正在列出我的用户去过的学校的信息TypeScript/Angular2-异常:TypeError:无法读取属性';推动';未定义的,typescript,angular,Typescript,Angular,我继续自学打字和安格拉尔,我仍然讨厌它,但我必须坚持下去。。。无论如何,我有一个组件,它从REST服务加载JSON数据。这个JSON数据非常复杂,所以我希望将其分解,并且在加载时,我希望将一些JSON分配给我定义的特定类型的数组。这是我的类型。。。我正在列出我的用户去过的学校的信息 export class UserSchool { constructor ( public schoolId: number, public
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
”并将其推送到数组或类型“UserSchool
”时,我收到一个错误EXCEPTION:TypeError:无法读取未定义的属性“push”
:我通过添加this.userSchools=[]
到我的构造函数可以解决这个问题,但它不能。然后我认为我的范围可能是个问题,所以在我的forEach中我尝试:
this.userInfo.data[0].items[0].entries.forEach(function (a) {
this.parent.userSchools.push(a); // still get an error
});
有人能告诉我为什么我不能推到我的对象数组吗?非常感谢 您应该对提供给
forEach
方法的回调使用箭头函数,以便能够使用词法this
:
this.userInfo.data[0].items[0].entries.forEach((a) => {
this.userSchools.push(a); // we get problems here...
});
在您的情况下,此
与组件的实例不对应
有关此箭头函数的词法用法的更多提示,请参见此链接:。您应该使用箭头函数来回调提供给
forEach
方法的回调,以便能够使用词法this
:
this.userInfo.data[0].items[0].entries.forEach((a) => {
this.userSchools.push(a); // we get problems here...
});
在您的情况下,此
与组件的实例不对应
有关此箭头函数词法的更多提示,请参见此链接:。Yep!你说得对!真不敢相信我错过了这个!哎呀!不用担心;-)在其他开发人员的代码中更容易看到这一点,而不是在他自己的代码中!是的!你说得对!真不敢相信我错过了这个!哎呀!不用担心;-)在其他开发人员的代码中更容易看到这一点,而不是在他自己的代码中!