简体   繁体   English

如何将表单控件值转换为角度对象?

[英]How to convert form control values to object in angular?

I have an endpoint which works only when I pass raw json when I call it , for example the raw json is , but the data on my frontend is coming from form data and the api does not accept it我有一个端点,它仅在我调用它时传递原始 json 时才起作用,例如原始 json 是 ,但是我前端的数据来自表单数据,而 api 不接受它

在此处输入图片说明 { "accountId": 4, "emailAddress": "wigin36937@ovooovo.com", "key": "PLFFNSWFH" } { "accountId": 4, "emailAddress": "wigin36937@ovooovo.com", "key": "PLFFNSWFH" }

But the api does not accept form data , so directly passing to the post request my this.verificationForm.value wont be accept and would result to error 400, what I want is how can I convert the data from verificationForm into an object like on the example above.但是api不接受表单数据,所以直接传递给post请求我的this.verificationForm.value不会被接受并且会导致错误400,我想要的是如何将verificationForm中的数据转换成一个对象上面的例子。

How do we get all the values from form data and convert it to an object before we pass it to the validateConfirmationCode param.我们如何从表单数据中获取所有值并将其转换为对象,然后再将其传递给 validateConfirmationCode 参数。 Thanks谢谢

verificationForm = this.fb.group({
    key : [null, Validators.required],
  },{
    updateOn:'submit'
  })

#Code #代码

 onSubmit = (transaction: string): void => {
    if (transaction == 'Verification') {
      this.verificationForm.addControl("key", new FormControl(this.code))
      this.verificationForm.addControl("accountId", new FormControl(this.accountId))
      this.verificationForm.addControl("emailAddress", new FormControl(this.email))
      this.isInProgress = true;
      this._userProfileService.validateConfirmationCode(this.verificationForm.value)
        .pipe(
          finalize(() => this.isInProgress = false),
        ).subscribe({
          next: (res) => {
            if (res.isSuccess) {
              this._notificationService.showSuccess('Success');
            }
          },
          error: err => this._notificationService.showError(err),
          complete: noop
        });

#code2 #code2

  validateConfirmationCode(data: DTO): Observable<any> {
    return this.httpRequestService.post<any>(`${apiBaseUrl}/code`, data);
  }

You can use an interface ICode :您可以使用接口 ICode :

export interface ICode {
    accountId: number;
    emailAddress: string;
    key: string;  
}

In the TS file you need to create an Object :在 TS 文件中,您需要创建一个 Object :

code = new Object() as ICode;

demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM