我在构造函数>> this.allStudents
中有错误
class Students {
public StudentsId: number;
public StudentsName: string;
public allStudents?: Students[];
constructor() {
this.allStudents = [
{ StudentsId: 100, StudentsName: 'Mahmoud'},
{ StudentsId: 101, StudentsName: 'Sami' },
{ StudentsId: 102, StudentsName: 'Osama' },
{ StudentsId: 103, StudentsName: 'Amer' },
{ StudentsId: 104, StudentsName: 'Ahmad' },
{ StudentsId: 105, StudentsName: 'Fadi' }
];
}
get getAllStudents() {
return null;
}
getStudentById(_studentsId) {
return this.allStudents.filter(x => x.StudentsId === _studentsId);
}
set addStudent(_student) {
}
}
我不知道为什么会发生这种错误。我需要一些帮助来解决这个问题。
我如何在课程students
中使用此界面?请检查界面IStudents
如下:
interface IStudents {
name: string,
age: number,
active:boolean
};
我不明白为什么你需要一个Students
的递归结构,所以用你感兴趣的属性定义一个Student
并引用它。它可以是类,接口或类型。
下面的示例将Student
与Students
列表分开,您可能希望更改名称以使其更明确。
interface Student {
StudentsId: number;
StudentsName: string;
}
class Students {
public StudentsId: number;
public StudentsName: string;
public allStudents: Student[] = [];
constructor() {
this.allStudents = [
{ StudentsId: 100, StudentsName: 'Mahmoud'},
{ StudentsId: 101, StudentsName: 'Sami' },
{ StudentsId: 102, StudentsName: 'Osama' },
{ StudentsId: 103, StudentsName: 'Amer' },
{ StudentsId: 104, StudentsName: 'Ahmad' },
{ StudentsId: 105, StudentsName: 'Fadi' }
];
}
get getAllStudents() {
return null;
}
getStudentById(_studentsId) {
return this.allStudents.filter(x => x.StudentsId === _studentsId);
}
set addStudent(_student) {
}
}
如果你真的需要一个学生层次结构,你可以这样做:
class Students {
public subStudents: Students[] = [];
constructor(public StudentsId: number, public StudentsName: string) {
this.subStudents = [
new Students(100, 'Mahmoud'),
new Students(101, 'Sami'),
new Students(102, 'Osama'),
new Students(103, 'Amer'),
new Students(104, 'Ahmad'),
new Students(105, 'Fadi'),
];
}
get getAllStudents() {
return null;
}
getStudentById(_studentsId) {
return this.subStudents.filter(x => x.StudentsId === _studentsId);
}
set addStudent(_student) {
}
}
我在两个代码示例中表达了我的观点,即空数组是不合需要的。您可以将其设置为非可选,并将其实例化为空数组,这样就无需在使用前对数组进行空值检查。