javascript - 来自另一个类的 Angular 4 设置属性

标签 javascript angular typescript

我有两个类:

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);

我在浏览器上调试:form的值可以获取成功,但是在新建User的时候,报错:

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

请指教。

最佳答案

你必须像这样初始化你的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;
}

关于javascript - 来自另一个类的 Angular 4 设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47216704/

相关文章:

javascript - 使用 jquery 1.11.3.min.js 时,jquery on click 事件未触发。

javascript - 选择值后删除 jquery 验证错误消息

javascript - 根据正确选择的单选按钮显示下拉菜单

angular - 我怎样才能只预加载其 parent 已被激活的模块?

angular - 为 Outlined 更改 mat-icon 中的主题

javascript - 禁用向下滚动会破坏 fullpage.js 中的菜单链接

angular - 有什么方法可以禁用 Angular 2 中的一组输入?

typescript - 是否可以根据数组值强类型化对象的键?

ios - 在使用共享扩展时从 swift 检索图像到 typescript

html - 如何使用 React 提供多个 HTML 文件?