如何在Angular中创建请求和响应模型



我想知道在Angular中处理请求和响应模型的正确方法是什么。我们应该总是为get和post操作创建两个不同的模型,还是像partial这样的关键字可以解决我们的问题?

比方说我想创建用户,API问我这些字段:

name: string;
username: string;
canRead: boolean;
roleId: string;

但当我们得到用户时,我们也有一些额外的字段。如何处理模型之间的差异

比方说当我们得到用户时的模型:

name: string; 
username: string;
canRead: boolean;
roleName: string;
roleId: string;

你可以有这样的东西:

api-name.model.ts

interface ApiNameRequest {
name: string;
username: string;
canRead: boolean;
roleId: string;
}
type ApiNameResponse = ApiNameRequest & {
roleName: string;
}

如果这两种类型差别太大(其中一种不包括第二种(,那么就制作两种类型
您将有一个干净的代码,并且您将知道roleName只出现在响应中,这与生成一种类型并具有roleName?相比,并想知道它何时可用,何时不可用。

L.E.让我们假设您的型号是:
request<->name, username, canRead, roleId, userId
response<->name, username, canRead, roleId, roleName

OPTION 1:合并类型

interface ApiNameModel {
name: string;
username: string;
canRead: boolean;
roleId: string;
userId?: string; // <- optional, just in Request
roleName?: string; // <- optional, just in Response
}

现在让我们假设我们进行API调用:

makeApiCall(url, request: ApiNameModel) {
code_to_call_the_api
}
...
const request: ApiNameModel = { 
name: 'a', 
username: 'a', 
canRead: true, 
roleId: 'a'
};
makeApiCall(url, request); // <- you can do this but API will say
// you miss userId, so you will get network error

OPTION 2:制作不同类型的

interface ApiNameRequest {
name: string;
username: string;
canRead: boolean;
roleId: string;
userId: string;
}
interface ApiNameResponse {
name: string;
username: string;
canRead: boolean;
roleId: string;
roleName: string;
}

现在让我们假设我们进行API调用:

makeApiCall(url, request: ApiNameRequest) {
code_to_call_the_api
}
...
const request: ApiNameRequest = { 
name: 'a', 
username: 'a', 
canRead: true, 
roleId: 'a'
}; // <- you get compile error here saying you miss userId
makeApiCall(url, request); // <- you can't get here until you fix typescript
// errors (the build will fail at compile)

如果您想使用模型yes,您可以在UserRoleDto.ts文件中创建dto(数据传输对象(,也可以在组件中创建模型。但就您的体系结构而言,第一种选择要好得多。如果您不使用模型,您可以将您的对象定义为";任何";。

Any类型用于表示任何JavaScript值。的值任何类型都支持与JavaScript中的值相同的操作,并且对Any上的操作执行最小静态类型检查价值观具体来说,任何名称的属性都可以通过Any值和Any值可以作为函数或构造函数调用带有任何参数列表。

最新更新