【问题标题】:TypeScript / Angular2 - EXCEPTION: TypeError: Cannot read property 'push' of undefinedTypeScript / Angular2 - 例外:TypeError:无法读取未定义的属性“推送”
【发布时间】:2016-12-06 22:53:19
【问题描述】:

我继续自学 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' 并将其推送到数组或类型 '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
});

那么有人可以告诉我为什么我不能推送到我的对象数组吗?非常感谢!

【问题讨论】:

    标签: typescript angular


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 是的!你是对的!不敢相信我错过了这个!哎呀!
    • 不用担心 ;-) 在其他开发人员的代码中比在他自己的代码中更容易看到这一点!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 2020-04-20
    • 2017-11-23
    • 2016-05-06
    相关资源
    最近更新 更多