首页 > 解决方案 > 如何将从下拉多选接收的数组值转换为角度5中的字符串

问题描述

我使用了一个材料下拉多选,用户可以通过它选择多个数据。当数据被发送到组件时,数据以数组格式接收,API 不接受将其插入数据库。我的查看代码:

      <mat-input-container>
    <input matInput type="number" formControlName="around" placeholder="Around" required >
    <p class="invalid-text" *ngIf="JifForm.controls.around.invalid &&
            (JifForm.controls.around.dirty || JifForm.controls.around.touched)">
      <span *ngIf="JifForm.controls.around.errors.required">Around is required.</span></p>
  </mat-input-container>

      <mat-form-field>
    <mat-select placeholder="Front Pass" formControlName="job_front_color" required multiple>
      <mat-option  value="pink">Pink</mat-option>
      <mat-option  value="black">Black</mat-option>
    </mat-select>
  </mat-form-field>

它以以下格式提供数据:

job_deno: 12345
job_front_color:(2) ["pink", "black"]

有没有办法让我job_front_color以字符串格式获取值,pink, black以便该值可以作为字符串通过 api

我通过以下代码将数据从表单传递到 api:

  onSubmit(form) {
  //console.log('AAAAAAAAAAAAAAAAAAAAAAAAAAAa', form);
return this._http.post('http://localhost:8000/api/v1/jobInstructionForm ', form, {headers: this.headers}).subscribe(res => {
  this.flashMsg.flashMsg('success', 'added', 'JIF added');
  this._router.navigate( ['pages/jif'] );
} );

}

标签: angularangular-materialangular5angular-arrays

解决方案


您可以使用Array.prototype.join()-文档

在你的情况下,你想要的是join(', ')

let arr = ["pink", "black"]
console.log(arr.join(', '));


编辑

如果您只想将该字符串发送到您的 API,只需执行以下操作:

onSubmit(form) {
  const stringOfColours = form.job_front_color.join(', );
  return this._http.post('http://localhost:8000/api/v1/jobInstructionForm ', stringOfColours, {
    headers: this.headers
  }).subscribe(res => {
    this.flashMsg.flashMsg('success', 'added', 'JIF added');
    this._router.navigate(['pages/jif']);
  });
}

推荐阅读