如何在类中将数字转换为枚举打字稿

时间:2019-04-06 19:23:49

标签: angular typescript enums angular6

我有这堂课

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
}

现在我正在按照以下步骤从服务器获取所有数据

this._service.getInstructorEvaluations(this.InstructorID).then(result => {
  if (result) {
    console.log(result);
    this.Events = result;

this.Events.forEach(element => {
  console.log(element.EvalMethodEnum);
    });
  }
});

“事件”属性包含InstructorEvent对象的列表...

但是它返回'undefined',知道我在做什么错吗?

1 个答案:

答案 0 :(得分:1)

设置this.Events = result时,this.Events中的项目不会被识别为InstructorEvents,并且如果仅将其强制转换,则不会初始化其中的属性。您需要定义一个构造函数并显式创建InstructorEvents。您的EvalMethodEnum函数中还有一个小的错字。

这应该有效:

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];
    }
}

或者,对于更简单的方法,您可以消除EvalMethodEnum调用并改为执行此操作:

this.Events.forEach((element: InstructorEvent) => {
    console.log(EvaluationMethodEnum[element.EvaluationMethod]);
});