AngularMaterial自动完成应调用API每次显示建议
创始人
2024-10-28 11:36:03
0

使用Observable和Subject来从API获得数据并更新自动完成建议。 每次输入时,使用自动完成控件中的事件,例如matAutocompleteSelected和matAutocompleteInput。 下面是示例代码,如何在每次输入时调用API并更新建议:

在component.ts文件中:

import { Component } from '@angular/core'; import { FormControl } from '@angular/forms'; import { HttpClient } from '@angular/common/http'; import { Observable, Subject } from 'rxjs'; import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators'; import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';

@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { searchControl = new FormControl(); searchResults: any[] = []; private searchTerms = new Subject();

constructor(private http: HttpClient) { this.searchTerms.pipe( debounceTime(300), distinctUntilChanged(), switchMap((term: string) => this.search(term)) ).subscribe(data => { this.searchResults = data; }); }

search(term: string): Observable { return this.http.get(https://api.example.com/search?q=${term}); }

onAutocompleteSelected(event: MatAutocompleteSelectedEvent): void { // handle selected value }

onInputChange(): void { const term = this.searchControl.value; if (term && term.length >= 3) { this.searchTerms.next(term); } } }

在component.html文件中:

{{ result.name }}

在这个例子中,每次在输入字段中键入至少3个字符时,searchTerms Subject将触发,并通过HTTP调用search方法来获取数据。然后通过

相关内容

热门资讯

教你透视!wepoker代打辅... 教你透视!wepoker代打辅助机器人,微乐家乡官方app,项目教程(有挂透明挂)-哔哩哔哩1、用户...
科普透视!德州局怎么透视,淘宝... 科普透视!德州局怎么透视,淘宝的微乐辅助是真的吗,演示教程(真的有挂)-哔哩哔哩1、这是跨平台的德州...
揭幕透视!德州局透视脚本,微乐... 揭幕透视!德州局透视脚本,微乐小程序辅助开发,资料教程(有挂存在)-哔哩哔哩1、上手简单,内置详细流...
教你透视!德普之星辅助器app... 教你透视!德普之星辅助器app,陕西微乐小程序辅助,窍要教程(有挂工具)-哔哩哔哩1、德普之星辅助器...
了解透视!wepoker科技辅... 了解透视!wepoker科技辅助器,微乐春天扑克开挂辅助插件,绝活教程(有挂方针)-哔哩哔哩1、不需...
辅助透视!werplan免费挂... 辅助透视!werplan免费挂下载,陕西微乐小程序脚本,手段教程(有挂技巧)-哔哩哔哩进入游戏-大厅...
专业透视!wejoker免费脚... 专业透视!wejoker免费脚本,微信小程序微乐家乡辅助器,经验教程(有挂详细)-哔哩哔哩wejok...
总结透视!wepoker数据分... 总结透视!wepoker数据分析工具,微乐自建房辅助软件有哪些功能,方案教程(有挂细节)-哔哩哔哩1...
普及透视!aapoker插件下... 普及透视!aapoker插件下载,微信小程序微乐辅助器下载,技法教程(有挂透视)-哔哩哔哩aapok...
揭幕透视!wepoker网页版... 揭幕透视!wepoker网页版透视方法,微乐自建房辅助可信吗,技法教程(有挂助手)-哔哩哔哩一、we...