【问题标题】:How to map angular form input to make a post request?如何映射角度表单输入以发出发布请求?
【发布时间】:2020-12-17 13:09:32
【问题描述】:

我需要帮助将表单输入映射到我的界面,以便我的发布请求的正文看起来像这样。

  "ListCars": [
    {
    "Car": "Toyota",
    "Color" : "Red" ,
    "Year": "2015"
    }
    ],
    "Type" : "rav4",
    }

我目前正在从我的表单中获取此输出

  Car: Toyota
    Color : Red 
    Year: 2015
    Type : rav4 

这是我的界面示例

expand interface Cars 
{
ListCars:  ListCars[],
Type: string ;
}

这就是我从表单中获取值并提出请求的方式

组件.ts

this.FormGroup = this.formBuilder.group({
      Car: new FormControl('', Validators.required),
      color: new FormControl('', [Validators.minLength(5), Validators.required]),
      year: new FormControl('', Validators.required),
      type: new FormControl('', Validators.required),
    });

submit(){
    if (this.reproGroup.valid) {
     const formValue: CarsInterface = this.FormGroup.value;

    this.service.postrequest(formValue.)
        .subscribe(response =>
      {

        });
      }
  }

service.ts

这就是我的发布请求的样子

 postrequest(carsInterface : CarsInterface ): Observable< output> {
      return this.http.post<output>(this .massReproDCQouteUrl, JSON.stringify(carsInterface ),
      {
        headers: {
          'Content-Type': 'application/json'
        }
      });
  }

【问题讨论】:

    标签: angular forms api interface mapping


    【解决方案1】:

    有几种方法可以解决这个问题

    一个是重构FormGroup

    this.FormGroup = this.formBuilder.group({
      ListCars: this.formBuilder.array([
          this.formBuilder.group({
              Car: ['', Validators.required],
              color: ['', [Validators.minLength(5), Validators.required]],
               year: ['', Validators.required],
          })          
      ]),
      type: ['', Validators.required]
    });
    

    另一个是在提交时更改 de FormGroup 值

    const { Car, color, year, type } = this.FormGroup.value;
    const formValue: CarsInterface = {
      ListCars: [{ Car, color, year }],
      type
    };
    

    Example on stackblitz

    【讨论】:

      猜你喜欢
      • 2019-10-10
      • 1970-01-01
      • 2014-02-16
      • 2018-11-10
      • 1970-01-01
      • 2019-12-04
      • 2019-09-19
      • 2019-09-07
      • 2018-01-26
      相关资源
      最近更新 更多