Reputation: 1200
I have a Reactive form in Angular for user registration. The setup of the reactive form means that the form data object
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.
Upvotes: 2
Views: 5694
Reputation: 7466
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
Upvotes: 1