typescript 错误类型错误:无法读取未定义的属性(读取"employeename")

g6ll5ycj  于 2022-12-27  发布在  TypeScript
关注(0)|答案(1)|浏览(132)

add-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>

add-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创建我得到:
无法读取属性employeename
我不知道我哪里做错了,有人能帮我解决这个问题吗?
先谢了。

k4aesqcs

k4aesqcs1#

注解中提到的第一个问题是,在使用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);
  }

  ...
}

相关问题