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方法来获取数据。然后通过

相关内容

热门资讯

玩家必备教程!德普辅助app,... 德普辅助appAI 游戏攻略黑科技上线本地缓存功能,离线查阅能力开挂。提前下载对应游戏攻略数据包,断...
我来向大家传授!wepoker... 您好,我来向大家传授!wepoker到底有没有透视,微扑克真的有挂插件(一贯是有辅助挂)这款游戏可以...
一分钟揭秘!德普之星有没有挂,... 『标题:当前标题』主打赛后复盘的 AI 游戏攻略黑科技走红,对局总结能力开挂。上传对局回放或者战绩截...
2分钟细说!wpk显示有作弊,... 2分钟细说!wpk显示有作弊,wepoker怎么开挂神器(原本是真的有辅助)AI 是一款可以让一直输...
分享认知!wepoker私人局... 一款 AI 游戏攻略黑科技工具上线,查攻略效率直接开挂。它整合版本更新、装备搭配、BOSS 打法、牌...
必知教程!wpk作弊,WPK透... 本地部署 AI 黑科技工具迎来新版本,不用上传文件到云端就能完成wpk作弊解析、 AI 处理、wpk...
必备教程!wepoker软件辅... 本地部署 AI 黑科技工具迎来新版本,不用上传文件到云端就能完成wepoker软件辅助程序解析、 A...
必看攻略!wpk免费辅助,we... 必看攻略!wpk免费辅助,wepoker开挂技巧安装(先前真的是有开挂)AI 智能体黑科技再上新,自...
科技分享!wepoker俱乐部... AI 黑科技赛道又上新,这款智能处理工具堪称效率开挂,专门面向短视频创作者打造。它打通脚本撰写、AI...
专业讨论!!德普之星私人局辅助... 『标题:当前标题』主打赛后复盘的 AI 游戏攻略黑科技走红,对局总结能力开挂。上传对局回放或者战绩截...