[英]How to convert number to enum typescript in class
I have this class 我有这堂课
export class InstructorEvent {
EventID: number;
EvaluationMethod: number;
get EvalMethodEnum(): EvaluationMethodEnum {
return
EvaluationMethodEnum[EvaluationMethodEnum[this.EvaluationMethod]];
}
}
export enum EvaluationMethodEnum {
None = -1,
Test = 0,
AssessmentForm = 1,
PassFailDecision = 2,
ParticipantSelfDeclaration = 3,
ActivityAccess = 4,
GradeDecision = 5,
Courseware = 6,
SCORM = 7,
Attendance = 8,
ObjectiveEvaluationManualGrade = 9,
ObjectiveEvaluationPassFail = 10,
ObjectiveEvaluationNone = 11,
ObjectiveEvaluationCustom = 12,
ObjectiveEvaluationAutoGrade = 14
}
Now i am getting all the data from the server as follow 现在我从服务器获取所有数据,如下所示
this._service.getInstructorEvaluations(this.InstructorID).then(result => {
if (result) {
console.log(result);
this.Events = result;
this.Events.forEach(element => {
console.log(element.EvalMethodEnum);
});
}
});
The 'Events' property contains list of InstructorEvent objects... “事件”属性包含InstructorEvent对象的列表...
But it returns 'undefined', any idea what am i doing wrong? 但是它返回“未定义”,知道我在做什么错吗?
When you set this.Events = result
, the items in this.Events
aren't recognized as InstructorEvents, and if you simply cast them, the properties inside don't get initialized. 当您设置
this.Events = result
, this.Events
中的项目将不会被识别为InstructorEvents,并且如果仅将其this.Events
则不会初始化其中的属性。 You need to define a constructor and explicitly create InstructorEvents. 您需要定义一个构造函数并显式创建InstructorEvents。 There's also a small typo in your EvalMethodEnum function.
您的EvalMethodEnum函数中还有一个小的错字。
This should work: 这应该工作:
this.Events.forEach((element) => {
element = new InstructorEvent(element.EventId, element.EvaluationMethod);
console.log(element.EvalMethodEnum);
});
export class InstructorEvent {
EventId: number;
EvaluationMethod: number;
constructor(eventId: number, evaluationMethod: number) {
this.EventID = eventID;
this.EvaluationMethod = evaluationMethod;
}
get EvalMethodEnum(): EvaluationMethodEnum {
return EvaluationMethodEnum[this.EvaluationMethod];
}
}
Or for a simpler approach, you could just eliminate the EvalMethodEnum call and do this instead: 或者,对于更简单的方法,您可以消除EvalMethodEnum调用并改为执行以下操作:
this.Events.forEach((element: InstructorEvent) => {
console.log(EvaluationMethodEnum[element.EvaluationMethod]);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.