php - 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" 。
[
我究竟做错了什么?
解决方案
这是由于选项的[value]属性而发生的。
如果您将 value 设置为 option.name,那么表单控件将只有名称而不是对象,您将不需要displayWith函数。
<mat-option *ngFor="let option of filteredOptions | async" [value]="option.name">
{{option.name}}
</mat-option>
您应该将选项设置为表单控件是有原因的。通常,您希望将选项 ID(在您的情况下为客户 ID)发送到服务器以识别所选记录。
推荐阅读
- java - 为什么 CAS(比较和交换)不等同于繁忙的等待循环?
- javascript - 加载更多分页
- git - 如何将 Visual Studio for Mac OS 连接到 Azure Dev Ops/VSTS?
- mediawiki - Mediawiki Special:用户登录
- python - 使用 selenium 和 python 在网页网格中抓取 javascript 数据
- javascript - 传单弹出窗口在 HTTPS 上无法正确执行,并且在 HTTP 上工作得更好
- javascript - Laravel + Vue.js MPA/SPA 混合结构的建议和思考
- ros - ROS:Gmapping & Lidar (YDLIDAR) - 看穿墙壁和障碍物?
- ruby - Watir 复杂元素的页面对象
- android - 为什么 Android Spinner onItemSelectedListener 有两个相同的参数