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

相关内容

热门资讯

分辨真假!竞技联盟透视插件,p... 这是一款非常优秀的竞技联盟透视插件 ia辅助检测软件,能够让你了解到竞技联盟透视插件中牌率当中全部隐...
最新通报!hhpoker万能辅... 最新通报!hhpoker万能辅助器,哈糖大菠萝有没有挂,微扑克教程(有挂辅助);小薇(透视辅助)致您...
一分钟揭秘!wepoker是不... 一分钟揭秘!wepoker是不是有人用挂,wepoker破解器激活码,详细教程(有挂攻略);玩家必备...
我来教大家!wepoker可以... 我来教大家!wepoker可以透视码,wepoker辅助器软件下载,玩家教程(有挂技巧);科技安装教...
一分钟了解!德普之星透视辅助插... 一分钟了解!德普之星透视辅助插件,wepokerplus开挂,AI教程(有挂软件)科技教程也叫必备教...
揭秘几款!wpk透视辅助方法,... 揭秘几款!wpk透视辅助方法,pokemmo脚本最新版,教你攻略(有挂透视);玩家必备必赢加哟《13...
一分钟了解!wepoker可以... 一分钟了解!wepoker可以开透视吗,德普之星透视辅助插件,线上教程(有挂攻略)1、玩家可以在德普...
发现玩家!WePoKer辅助器... 发现玩家!WePoKer辅助器,拱趴大菠萝挂哪里,实用技巧(有挂神器);玩家必备必赢加哟《13670...
一分钟了解!wepoker怎么... 一分钟了解!wepoker怎么获得好牌,wepoker辅助器软件下载,必胜教程(有挂技巧);大神普及...
一分钟秒懂!wepoker有辅... 一分钟秒懂!wepoker有辅助工具吗,智星德州有脚本吗,新2025教程(有挂技巧);1分钟了解详细...