我正在按服务获取对象列表。这些列表在result.data中。但是result.data中的对象具有属性“ Text”和“ Value”。但我想将列表绑定到具有属性“标签”和“值”的数组。在C#中,我们可以通过Select做到这一点。所以我在下面像c#这样写。但是我该如何在角度为6的打字稿中做呢?
this.serviceHelper.getStudentTypes().subscribe(
result => {
this.studentTypes = result.data
.Select(p => new SelectItem {//???
label=p.Text, //???
value=p.Value //???
});
}
);
selectItem.ts
export interface SelectItem {
label?: string;
value: any;
styleClass?: string;
icon?: string;
title?: string;
disabled?: boolean;
}
您几乎可以在JS / TS中进行相同的操作,只需使用map
,以及创建JS对象文字的corect方法:
this.serviceHelper.getStudentTypes().subscribe(
result => {
this.studentTypes = result.data
.map(p => ({
label:p.Text,
value:p.Value
}));
}
);
上面的代码假定getStudentTypes
返回Observable<{ Text: string, Value: string }[]>
或等效值。
编辑
由于希望新数组的类型为SelectItem[]
您可以在map
需要时显式指定它(这有助于某些错误的错误消息),但这不是必需的。如果this.studentTypes
类型为asSelectItem[]
且返回的map
兼容于,SelectItem
那么所有功能都将按预期工作(由于SelectItem
是接口而不是类,我们可以将任何兼容的对象常量分配给该类型的变量,这就是结构类型在typescript中的工作方式)
该显map
式返回的显式版本为SelectItem[]
:
this.serviceHelper.getStudentTypes().subscribe(
result => {
this.studentTypes = result.data
.map<SelectItem>(p => ({
label:p.Text,
value:p.Value
}));
}
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句