【问题标题】:Mapping two objects in Angular 7 Typescript在 Angular 7 Typescript 中映射两个对象
【发布时间】:2019-03-10 00:31:51
【问题描述】:

我在 Angular 中有一个用于用户注册的响应式表单。反应式表单的设置意味着表单数据对象

与我的视图模型对象不同

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

明确地说,在表单对象中,两个密码属性嵌套在单独的“matching_passwords”对象中。

我的表单对象在 onSubmit(value) 方法中被捕获

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

将值传递给需要 RegisterViewModel 对象的服务方法。

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

在不改变我的表单结构以使其与 RegisterViewModel 结构完美匹配的情况下,我如何将这些不同的对象相互映射?

如何将表单模型传递给注册方法 register(viewModel: RegisterViewModel)?我希望我的 RegisterViewModel 从我的表单中接收电子邮件、用户名、密码和密码确认字符串。

【问题讨论】:

  • 我想提供帮助,但我不确定我是否理解您将它们映射到另一个的意思。你能提供一个你瞄准的结果的例子吗
  • @Koop4 如何将表单模型传递给 register 方法: register(viewModel: RegisterViewModel),它接受不同的 RegisterViewModel 对象?我希望我的 RegisterViewModel 从我的表单中接收电子邮件、用户名、密码和密码确认字符串。

标签: angular typescript


【解决方案1】:

您可以简单地从表单值构建对象。根据您的图片,它看起来像:

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

然后你打电话

this.accountService.register(viewModelObject)
// ... following stays the same

【讨论】:

    猜你喜欢
    • 2021-01-11
    • 2016-11-07
    • 2018-02-10
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多