我正在制作一个初学者网站,到目前为止一切都很好,但我现在有一个奇怪的问题。
当在node.js控制台中键入ng serve --open以在localhost上启动站点时,我收到此消息 - >
src / app / department-detail / department-detail.component.ts(59,32)中的错误:错误TS2339:类型'部门'上不存在属性'employee'
我的代码是:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { Department } from '../department';
import { DepartmentService } from '../department.service';
import { Employee } from '../employee';
import { EmployeeService } from '../employee.service';
@Component({
selector: 'app-department-detail',
templateUrl: './department-detail.component.html',
styleUrls: ['./department-detail.component.css']
})
export class DepartmentDetailComponent implements OnInit {
department : Department ;
employees: Employee[];
emp: Employee;
average:number=1;
constructor(private route: ActivatedRoute, private departmentService: DepartmentService, private location: Location,private employeeService: EmployeeService) { }
ngOnInit() {
this.getDepartment();
this.getEmployees();
}
getDepartment(): void{
const id = +this.route.snapshot.paramMap.get('id');
this.departmentService.getDepartment(id).subscribe(department => this.department = department)
}
goBack(): void{
this.location.back();
}
save(): void {
this.departmentService.updateDepartment(this.department);
this.goBack();
}
getEmployees(): void {
this.employeeService.getEmployees().
subscribe(employees => this.employees = employees);
}
Select(firstname:string){
firstname = firstname.trim();
if(!firstname){return;}
this.employeeService.getEmployeeByName(firstname).subscribe(Employee => this.emp = Employee);
}
Delete():void{
this.emp = null;
this.average = 1;
}
Show():void{
this.Select(this.department.employee); // this cant be true
this.average = null;
}
}
问题出在最后
显示功能
如果我删除员工并保存,然后再次添加它,那么边工作,但否则它不会。
这是我的部门组成部分。
export class Department{
id: number;
name: string;
location: string;
menId: number;
static Id:number = 1;
constructor(name: string,location: string) {
this.id = Department.Id++;
this.name = name;
this.location = location;
this.menId = 0;
}
}
我不确定是否应该在Department组件中添加Employee类型的属性。
如果你看一下Department
课程,你会注意到它实际上没有雇员财产。你应该添加一个这样的:
export class Department{
id: number;
name: string;
location: string;
menId: number;
static Id:number = 1;
employee: string; // New employee property, type based on the Show method signature
constructor(name: string,location: string) {
this.id = Department.Id++;
this.name = name;
this.location = location;
this.menId = 0;
}
}
添加属性后,您可能会收到另一个错误,这次是在应用程序运行时,说firstname is undefined
。如果你得到这个错误,它会被Select
方法抛出,你首先尝试修剪名称,然后检查它是定义的还是非空的。为了防止错误,你应该简单地交换Select
方法的第一行和第二行,使它们看起来像这样:
if(!firstname){ return; }
firstname = firstname.trim();