【问题标题】:Cannot read property 'name' of undefined after creating a model创建模型后无法读取未定义的属性“名称”
【发布时间】:2019-03-17 06:16:33
【问题描述】:

我对 Angular 很陌生。我定义了一个导出一些字段的模型。在我将所有用户对象写入我的 ts 文件之前。现在我创建模型后出现错误:

ERROR TypeError: Cannot read property 'name' of undefined

我该如何解决这个错误?

这些是我的代码。

user.model.ts

export class User {
    name: string = '';
    email: string = '';
    password: any = '';
}

register.component.ts

import { User } from '../../models/user.model';
export class RegisterComponent implements OnInit {
    public form: User;
}

register.html

<form #signupForm=ngForm (ngSubmit)="onSubmit()">
    <input type="text" name="name" #name="ngModel" [(ngModel)]="form.name" class="form-control" id="inputname3" placeholder="Enter Name" required>

【问题讨论】:

  • 你在哪里设置了form对象

标签: angular angular6


【解决方案1】:

你需要创建一个 User 的实例,

 public form: User;

constructor(){
  this.form = new User();
}

【讨论】:

【解决方案2】:

我要做的是创建一个 interface UserRef 用于类型检查

user.ts

export interface UserRef {
    name: string;
    email: string;
    password: any;
}

register.component.ts

import { UserRef } from '../../contracts/user';
import { User } from '../../models/user.model';
export class RegisterComponent implements OnInit {
    public form: FormGroup;
    public user: UserRef;

    ngOnInit() {
       this.user = new User()
       // form setup
       // this.form = ...

    }
}

user.model.ts 应该看起来像

export class User {
    name: string = '';
    email: string = '';
    password: any = '';
    constructor() {}
}

【讨论】:

    【解决方案3】:

    register.component.ts

    import { User } from '../../models/user.model';
    export class RegisterComponent implements OnInit {
       public form: User = {};
    }
    

    请试试这个。

    【讨论】:

    • 我收到此错误 TS2322:类型“{}”不可分配给类型“用户”。
    • "export interface User { name: string, email: string, password:any, }" 请试试这个user.model.ts
    【解决方案4】:

    只需在使用之前初始化您的 form 对象。

    工作副本在这里https://stackblitz.com/edit/angular-xn211g

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 2022-01-22
      • 2021-11-13
      • 2022-01-14
      • 2022-06-22
      • 2017-02-06
      相关资源
      最近更新 更多