【问题标题】:ERROR TypeError: Cannot read properties of undefined (reading 'employeename')错误 TypeError:无法读取未定义的属性(读取 \'employeename\')
【发布时间】:2022-12-24 08:27:52
【问题描述】:

添加-employee.html

<div class="col-md-6 offset-md-3">
    <h3> Create Employee </h3>
    <form (ngSubmit) = "onSubmit()">

        <div class="form-group">
            <label>Name</label>
            <input type="text" class ="form-control" id = "employeename"
                [(ngModel)] = "employee.employeename" name = "employeename">
        </div>

        <div class="form-group">
            <label>Age</label>
            <input  class ="form-control" id = "age"
                [(ngModel)] = "employee.age" name = "age">
        </div>

        <button class = "btn btn-success" type ="submit">Submit</button>

    </form>
</div> 

添加-employee.ts

import { Component, OnInit } from '@angular/core';
import { Employee } from '../employee';
import { EmployeeserviceService } from '../employeeservice.service';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-add-employee',
  templateUrl: './add-employee.component.html',
  styleUrls: ['./add-employee.component.css']
})
export class AddEmployeeComponent implements OnInit {

  employee !: Employee;

  constructor(private employeeService:EmployeeserviceService) { }

  ngOnInit(): void {
  }

  onSubmit(){
    console.log(this.employee);

    this.employeeService.saveEmployee(this.employee).subscribe(data=>{
      console.log(data);
    })
  }

}

我是 Angular 的新手,我正在尝试创建一个示例员工 CRUD 应用程序以获得实践经验。但是在创建 POST API 创建时我得到:

无法读取属性员工姓名

我不知道我在哪里做错了任何人都可以帮我解决这个问题吗?

提前致谢。

【问题讨论】:

  • 从您的代码中,您没有为 employee 初始化值(实例)。在ngOnInit()方法中添加这一行:this.employee = new Employee(0, "", 0);
  • @YongShun 有没有其他方法可以解决这个问题,因为我不想在输入字段中显示零值。
  • 考虑将 age 属性设置为可为空。 age : number | null 并用null 初始化age。这不会在文本框中显示零作为初始值,但是您可能需要编写年龄字段验证以确保用户已填写 age(如果 age 是必填字段)。
  • 嗨@YongShun 可以给我一个小代码 sn-p 来使变量为空。我对如何使年龄为零感到非常困惑。

标签: angular typescript angular-forms


【解决方案1】:

评论中提到的第一个问题是您错过了在使用之前将 Employee 实例初始化为 employee 变量。将实例初始化为 employee 变量将解决此问题。

export class AddEmployeeComponent implements OnInit {

  ...

  ngOnInit(): void {
    this.employee = new Employee(0, "", 0);
  }

  ...

}

为了隐藏初始年龄值 (0),您可以考虑将 Employee 类中的 age 属性应用为可空。

export class Employee {
    id: number;
    employeename: string;
    age: number | null;

    constructor(id: number, employeename: string, age: number | null){
        this.id=id;
        this.employeename=employeename;
        this.age=age;
    }
}

并将age初始化为null

export class AddEmployeeComponent implements OnInit {

 ...

  ngOnInit(): void {
    this.employee = new Employee(0, "", null);
  }

  ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-26
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    • 2017-05-05
    • 2019-04-05
    相关资源
    最近更新 更多