2

i need to pass enum type to server . but when i send the form to server it send enum fild by type string .

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????

1

1 Answer 1

4

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 ? Please note your payString data have to be the same with your enum key

For example:

PayTypes['Free'] // This will work

And

PayTypes['free'] // This won't
Sign up to request clarification or add additional context in comments.

3 Comments

still send it string
@kianoushdortaj working fine here!
@kianoushdortaj check my answer again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.