2

I have a Reactive form in Angular for user registration. The setup of the reactive form means that the form data object

enter image description here

is different from my viewmodel object

export interface RegisterViewModel {
UserName: string;
Email: string;
Password: string;
ConfirmPassword: string; }

To be explicit, in the form object, the two password properties are nested in a seprate 'matching_passwords' object.

My form object is captured in the onSubmit(value) method

  onSubmit(value) {
this.accountService.register(value)
.pipe(first())
.subscribe(
  data => {
    console.log('successful registration');
    this.router.navigate(['/login']);
  },
  error => {
    console.log('unsuccessful registration');
  }); }

which passes the value to the service method which expects the RegisterViewModel object.

  register(viewModel: RegisterViewModel) {
    return this.http.post<any>('api/Account/Register', viewModel, httpOptions)
      .pipe(map(data => {
        return data;
      }));
  }

Without changing my form structure so that is perfectly matches the RegisterViewModel structure, how do I map these different objects to one another?

How can I pass the form model to the register method, register(viewModel: RegisterViewModel)? I want my RegisterViewModel to recieve the email, username, password and passwordconfirm strings from my form.

2
  • 1
    I'd like to help but I'm not sure I understood what you mean by mapping them to one other. Could u provide an example of the result you rr aiming fir Commented Mar 9, 2019 at 16:10
  • @Koop4 How can I pass the form model to the register method: register(viewModel: RegisterViewModel), which accepts the diffrent RegisterViewModel object? I want my RegisterViewModel to recieve the email, username, password and passwordconfirm strings from my form. Commented Mar 9, 2019 at 16:16

1 Answer 1

1

You can simply build the object from the form values. Based on your picture, that would look like:

// say your form value object is `form_values` (instead of `value` in your code)
const viewModelObject = <RegisterViewModel> {
  UserName: form_values.userName,
  Email: form_values.email,
  Password: form_values.matching_passwords.password,
  ConfirmPassword: form_values.matching_passwords.confirmPassword
};

Then you call

this.accountService.register(viewModelObject)
// ... following stays the same
Sign up to request clarification or add additional context in comments.

Comments

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.