[英]What is the best way to create model class in angular?
I want suggestion on how to create model class in angular for interacting with database Let's say my spring JPA entity is Environment.java我想要关于如何以角度创建模型类以与数据库交互的建议假设我的 spring JPA 实体是 Environment.java
@Entity
public class Environment {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE)
@Column(name = "ENV_SId", nullable = false)
private Long envSid;
@Column(name = "ENV_NAME",nullable = false)
private String envName;
public Long getEnvSid() {
return envSid;
}
public void setEnvSid(Long envSid) {
this.envSid = envSid;
}
public String getEnvName() {
return envName;
}
public void setEnvName(String envName) {
this.envName = envName;
}
}
My angular model class is environment.model.ts我的角度模型类是 environment.model.ts
export class Environment {
envName: string;
}
Because the primary key is auto-generated I will use my environment.model.ts class to post data to the server.因为主键是自动生成的,所以我将使用我的 environment.model.ts 类将数据发布到服务器。 But while getting the data I also need the primary key
envSid
together with envName
in my angular app.但是在获取数据的同时,我还需要主键
envSid
和我的 angular 应用程序中的envName
。 Do I need to create two different models for the two cases?我是否需要为这两种情况创建两种不同的模型? One model with only
envName
while doing POST request and one model with envSid
and envName
while doing GET request?一种在执行 POST 请求时只有
envName
模型和envName
在执行 GET 请求时具有envSid
和envName
模型?
That's a question I have been pondering quite a bit, and below is my conclusion.这是我一直在思考的一个问题,下面是我的结论。 I'm happy to discuss whether it always makes sense or not.
我很高兴讨论它是否总是有意义的。
The principle I use is: your model should have all fields that make sense for a complete object.我使用的原则是:您的模型应该包含对完整对象有意义的所有字段。
In your case, it means that id
should be part of the model.在您的情况下,这意味着
id
应该是模型的一部分。
The rationale behind that is:这背后的理由是:
POST
request you mention) is not yet an object , but just the initialization data.POST
请求)还不是 object ,而只是初始化数据,这是有道理的。 Sometimes, it might not even map to the specific fields of your model, so it is good practice to keep them separate. In your case, I would indeed have 2 models: EnvironmentInitializeData
and EnvironmentModel
or whatever name, you get the idea.在您的情况下,我确实有 2 个模型:
EnvironmentInitializeData
和EnvironmentModel
或任何名称,您明白了。
By the way, the initialization data does not always need to be expressed as a type since it is often used only once and in a straightforward manner.顺便说一下,初始化数据并不总是需要表示为一种类型,因为它通常只使用一次并且以一种直接的方式使用。
The good practice is to create 1 model Interface per Data Transfer Object .好的做法是为每个数据传输对象创建 1 个模型接口。 So in your case, you should do something like that:
所以在你的情况下,你应该做这样的事情:
environment.model.ts环境.model.ts
export interface Environment {
envName: string;
envSid: number;
}
environmentToPost.model.ts environmentToPost.model.ts
export interface EnvironmentToPost {
envName: string;
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.