来自另一个类

时间:2017-11-10 06:16:14

标签: javascript angular typescript

我有2个类,如:

UserInfo

export class UserInfo {
    id: number;
    fullName: string;
    firstName: string;
    lastName: string;
    address: string;
    dob: string
}

用户

import {UserInfo} from './User-Info'

export class User {
    id: number;
    userName: String;
    status: String;
    userInfo: UserInfo;

    constructor(firstName: string, lastName: string, address: string){
        this.userInfo.firstName = firstName;
        this.userInfo.lastName = lastName;
        this.userInfo.address = address;
      }

} 我正在使用FormGroup来设置数据值:

let user: User = new User(
    this.userForm.controls['firstName'].value,
    this.userForm.controls['lastName'].value,
    this.userForm.controls['address'].value);
this.userService.createUser(user);

我在浏览器上调试:表单的值可以成功但是在创建新用户时,我有一条错误消息:

ERROR TypeError: Cannot set property 'firstName' of undefined
    at new User (User.ts:10)

请告知。

1 个答案:

答案 0 :(得分:3)

您必须为您的userInfo变量启用类似

的变量
userInfo:UserInfo = new UserInfo();

或构造函数

constructor(firstName: string, lastName: string, address: string) {
    this.userInfor=new UserInfo();

    this.userInfo.firstName = firstName;
    this.userInfo.lastName = lastName;
    this.userInfo.address = address;
}