[英]convert string to enum Value in angular 8
i need to pass enum type
to server .我需要将
enum type
传递给服务器。 but when i send the form to server it send enum fild
by type string
.但是当我将表单发送到服务器时,它会按类型
string
发送enum fild
。
this is my enum :这是我的枚举:
export enum PayTypes {
Free,
Subscribe
}
and this is my form :这是我的表格:
createForm(): void {
this.lessonAddForm = new FormGroup({
payType: new FormControl('', Validators.required),
});
}
addLesson(): void {
const payString = PayTypes[this.lessonAddForm.controls['payType'].value];
const payType: PayTypes = PayTypes[payString];
this.lessonAdd = this.lessonAddForm.value;
this.lessonAdd.payType = payType;
this.subscriptions = this.lessonService
.add(this.lessonAdd)
.subscribe(
res => {
if (res.success === true) {
this.alertService.success('', 'GENERAL.ADD_SUCCESS');
this.backToMenu();
}
}
);
}
and i try for convert string to enum by this way :我尝试通过这种方式将字符串转换为枚举:
const payString = PayTypes[this.lessonAddForm.controls['payType'].value];
const payType: PayTypes = PayTypes[payString];
this.lessonAdd = this.lessonAddForm.value;
this.lessonAdd.payType = payType;
but it not work .但它不起作用。
How can i solve this Problem????我怎么解决这个问题????
You must convert the value inside the square bracket to string like this您必须将方括号内的值转换为这样的字符串
const payType: PayTypes = PayTypes[payString.toString()];
Also you can view this post你也可以查看这个帖子
Update: Check how you get payString data does it match with your enum definition ?更新:检查您如何获取 payString 数据是否与您的枚举定义匹配? Please note your payString data have to be the same with your enum key
请注意您的 payString 数据必须与您的枚举键相同
For example:例如:
PayTypes['Free'] // This will work
And和
PayTypes['free'] // This won't
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.