【发布时间】:2020-06-05 06:08:20
【问题描述】:
如何使用以下两个类将数组列表从源映射到目标? 需要 DTO 映射到查找数组。一直在测试地图功能,还是不行。另外,我们应该将 mapFromSourceAddressDto 方法设为单独的 Export 函数,还是在 Lookup 类本身内部,这样会更容易吗?
后端 DTO API 模型可能会更改,因此尝试创建一种类型安全的方式来映射子集列,并在 DTO 列名称更改时收到通知。
export class SourceOfAddressDto {
sourceOfAddressId: number | undefined;
sourceOfAddressCode: string | undefined;
sourceOfAddressDescription: string | undefined;
sourceOfAddressLabel: string | undefined;
createDate: date;
userId: string;
}
export class SourceOfAddressLookup {
sourceOfAddressId: number | undefined;
sourceOfAddressCode: string | undefined;
sourceOfAddressDescription: string | undefined;
sourceOfAddressLabel: string | undefined;
}
export function mapFromSourceOfAddressDto(sourceOfAddressDto: SourceOfAddressDto){
const sourceOfAddressLookup = new SourceOfAddressLookup();
sourceOfAddressLookup .sourceOfAddressId = sourceOfAddressDto.sourceOfAddressId
sourceOfAddressLookup .sourceOfAddressCode = sourceOfAddressDto.sourceOfAddressCode;
sourceOfAddressLookup .sourceOfAddressDescription = sourceOfAddressDto.sourceOfAddressDescription
sourceOfAddressLookup .sourceOfAddressLabel = sourceOfAddressDto.sourceOfAddressLabel;
return sourceOfAddressLookup ;
}
目标: Take an Array<SourceofAddressDto> ---> Array<SourceOfAddressLookup>
尝试的解决方案:
寻找更清洁的方式,
public addressSourceList: Array<SourceOfAddressLookup>;
if (addressSourceListDto.length > 0){
for (let i = 0; i < addressSourceListDto.length; ++i ) {
this.addressSourceList[i] = mapFromSourceOfAddressDto(addressSourceListDto[i])
}
}
【问题讨论】:
-
恐怕我不明白这个问题。您能否将代码编辑为minimal reproducible example,它清楚地显示您正在尝试做什么以及它在哪里不起作用?祝你好运!
-
你是怎么调用
mapFromSourceOfAddressDto函数的? -
查看以上@jcalz 尝试的解决方案
-
查看@HereticMonkey 上面的尝试解决方案可能会有所帮助
-
您需要类而不是接口是否有特殊原因?类应该初始化它们的属性,所以
createDate: date; userId: string;是错误的。而date不是已知类型;你的意思是Date?
标签: javascript angular typescript