如果您使用的是Angular和Material,您可能会发现Material的自动完成组件无法使用POST请求。解决这个问题的方法是在自动完成组件中手动添加发送POST请求的逻辑。在您的组件中,您可以使用HttpClient发送POST请求,并将响应结果映射到您自己的数据模型中。
以下是示例代码:
HTML模板:
组件:
import { Component, OnInit } from "@angular/core"; import { FormControl } from "@angular/forms"; import { HttpClient } from "@angular/common/http"; import { Observable } from "rxjs"; import { map, startWith } from "rxjs/operators";
@Component({ selector: "app-my-component", templateUrl: "./my-component.component.html", styleUrls: ["./my-component.component.css"], }) export class MyComponentComponent implements OnInit { myControl = new FormControl(); options: string[] = ["One", "Two", "Three"];
filteredOptions: Observable
constructor(private http: HttpClient) {}
ngOnInit() { this.filteredOptions = this.myControl.valueChanges.pipe( startWith(""), map((value) => this._filter(value)) ); }
displayFn(option: string): string { return option ? option : ""; }
private _filter(value: string): string[] { const filterValue = value.toLowerCase(); const url = "YOUR_POST_ENDPOINT"; this.http.post(url, { search: filterValue }).subscribe((response) => { // extract your resulting options from the response // and assign them to the this.options variable }); return this.options.filter((option) => option.toLowerCase().includes(filterValue) ); } }
在这个例子中,我们将在用户输入更改时使用valueChanges流来检测输入的值。我们将调用_filter()函数,并将输入值作为参数传递。在这个函数中,我们将发送一个POST请求(使用HttpClient)并将输入值传递给API端点。在API端点,您可以处理POST请求并返回所需的选项列表。返回的选项列表将被赋值到this.options变量中,并将用于