我正在为多种类型的用户数据使用常见的反应形式。就像一些用户有额外的数据,如老师,学生,警卫等。表格从下拉列表中选择
我想根据所选用户发送特定的数据对象。我创建了一个名为" user"包含所有common和diff字段。现在我想发送数据如下
selectedUser:string; //form selected like teacher etc
submit(data){
if(selectedUser === 'Teacher'){
let techobj =new User(data.name,data.address,data.degree);
this.userservice.post(url,teachobj);
}
if(selectedUser === 'Student'){
let stuobj =new User(data.name,data.address,data.semester);
this.userservice.post(url,stuobj);
}
..... so on
}
模型类
export class User{
//all fields here
constructor(name :string,address:string,semester ?:string ,degree?:string)
}
问题 不能使用像Java或C#
这样的diff params重载构造函数或创建对象答案 0 :(得分:1)
您可以创建一个具有强制性和可选属性的接口,您需要在下面的特殊情况下传递
export interface IUser{
name: string;
address: string;
semester?: string,
degree?: string
}
此处的名称,地址对每个案例都是强制性的,但学期和学位可以根据条件传递。
您可以在User
类的构造函数中使用此接口,如下所示,以设置属性的值。
export class User{
//all fields here
public name: string;
public address: string;
public semester?: string;
public degree?: string;
constructor(user:IUser) {
this.name = user.name;
this.address = user.address;
this.semester = user.semester;
this.degree = user.degree;
}
}
最后,您可以创建类的实例,如下面的方法 -
let data2:IUser = { name: data.name, address: data.address, degree: data.degree};
let techobj = new User(data2);
或者你可以这样做
let techobj2 = new User({ name: data.name, address: data.address, degree: data.degree});
同样对于Student
,您可以像这样创建实例 -
let techobj3 = new User({ name: data.name, address: data.address, semester:data.semester });
这是完整的代码 -
export interface IUser{
name: string;
address: string;
semester?: string,
degree?: string
}
export class User{
//all fields here
public name: string;
public address: string;
public semester?: string;
public degree?: string;
constructor(user:IUser) {
this.name = user.name;
this.address = user.address;
this.semester = user.semester;
this.degree = user.degree;
}
}
let data:IUser = { name: "Niladri", address: "123", degree: "GRAD" };
let techobj = new User(data);
///OR
let techobj2 = new User({ name: "Niladri", address: "123", degree: "GRAD" });
//Similary
let techobj3 = new User({ name: "Niladri", address: "123", semester:"6th" });
console.log(techobj2.degree); //GRAD
console.log(techobj3.semester); //6th
您的服务电话应该是这样的 -
selectedUser:string; //form selected like teacher etc
submit(data){
if(selectedUser === 'Teacher'){
let techobj =new User({ name: data.name, address: data.address, degree: data.degree});
this.userservice.post(url,teachobj);
}
if(selectedUser === 'Student'){
let stuobj =new User({ name: data.name, address: data.address, semester:data.semester });
this.userservice.post(url,stuobj);
}
..... so on
}
P.S - 如果你在当前的构造函数中为不需要的参数传递null,那么它也可以工作
编辑2:另一种方法是创建基类User
并从该类继承以创建Student
和Teacher
类,然后在构造函数中调用super()
子类将name,address
属性值传递给基类User
类。但是在这种情况下会有许多子类,具体取决于if条件的数量
工作演示:
答案 1 :(得分:0)
也许考虑创建一个类User,其中包含Teacher和Student相同的所有字段。然后,您可以为教师和学生创建单独的类,这些类将扩展类User,并包含对其唯一的其他字段,在这种情况下为教师的学位,以及学生的学期。 也许这会有所帮助: Extending Classes in Typescript。