首页 > 解决方案 > Angular:使用 api 数据填充的材料自动完成返回 JSON 值

问题描述

我是 Angular 新手,正在开发一个小型分类帐应用程序。在其中,用户必须从材料自动完成字段中选择客户,该字段填充有来自 API 的数据。像这样:

PHP 后端

    <?php

require 'database.php';

$nhiu_customers = [];
$sql = "SELECT cust_name FROM customer_table";

if($result = mysqli_query($con,$sql))
{
  $i = 0;
  while($row = mysqli_fetch_assoc($result))
  {
    $customers[$i]['cust_name'] = $row['cust_name'];
    $i++;
  }

  echo json_encode($customers);
}
else
{
  http_response_code(404);
}

角组件.html

{{incomeForm.value | json}}
<form [formGroup]="Form">

<p> <mat-form-field class="customer">
    <input type="text" matInput placeholder="Select Customer" 
    [matAutocomplete]="auto" formControlName="customerName">
    <mat-autocomplete #auto="matAutocomplete" [displayWith]="getOptionText">
    <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{option.cust_name}}
    </mat-option>
    </mat-autocomplete>
</mat-form-field> 

</p>

角组件.TS

import { Component, OnInit, Injectable } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import {Observable, of, Subscription} from 'rxjs';
import {map, startWith, switchMap, tap, debounceTime} from 'rxjs/operators';
import { ApiService } from '../api.service';

export class Component implements OnInit{

Form = new FormGroup({
  customerName: new FormControl('')
});

filteredOptions: Observable<string>;

ngOnInit() {
  this.filteredOptions = this.Form.controls['customerName'].valueChanges.pipe(
    startWith(""),
    debounceTime(300),
    switchMap(value => this.doFilter(value))
  );

  doFilter(value){
    return this.service.getData().pipe(
      map(response =>
        response.filter(option => {
          return option.cust_name.indexOf(value) === 0;
        })
      )
    );

  }

  getOptionText(option) {
    return  option.cust_name;
  }

}

角度 API 服务

export class ApiService {

  constructor(private httpClient: HttpClient) { }

opts = [];

getData() {
  return this.opts.length
    ? of(this.opts)
    : this.httpClient
    .get<any>("http://localhost/api/read.php")
    .pipe(tap(data => (this.opts = data)));

}
}

材料自动完成工作正常,它从 api 填充数据。但问题是,当我从列表中选择客户姓名时,我必须发布的表单的 JSON 包采用客户姓名的 JSON 编码值,而不是常规文本输入(见下图)。理想情况下,表单应该为 formControl customerName生成 JSON 值 "customerName": "Customer Name" 。

[https://i.stack.imgur.com/pcDg4.jpg

我究竟做错了什么?

标签: phpangularapiangular-material

解决方案


这是由于选项的[value]属性而发生的。

如果您将 value 设置为 option.name,那么表单控件将只有名称而不是对象,您将不需要displayWith函数。

  <mat-option *ngFor="let option of filteredOptions | async" [value]="option.name">
    {{option.name}}
  </mat-option>

您应该将选项设置为表单控件是有原因的。通常,您希望将选项 ID(在您的情况下为客户 ID)发送到服务器以识别所选记录。

显示自动完成的示例


推荐阅读