我在构造函数中有错误>> 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
};
答案 0 :(得分:1)
我看不到为什么需要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) {
}
}
我在两个代码示例中都表达了我的观点,即不希望使用null数组。您可以将其设为非可选并将其实例化为空数组,从而无需在使用前对数组进行空检查。