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

相关内容

热门资讯

四分钟了解!开心泉州作必弊!果... 四分钟了解!开心泉州作必弊!果然存在有辅助技巧(有挂细节)-哔哩哔哩1、开心泉州作必弊透视辅助软件激...
三分钟了解!情怀麻烦将关春天辅... 三分钟了解!情怀麻烦将关春天辅助!其实一直总是有辅助神器(有挂教学)-哔哩哔哩1、完成情怀麻烦将关春...
8分钟了解!福建十三水软件开发... 8分钟了解!福建十三水软件开发!一直有辅助工具(有挂秘诀)-哔哩哔哩该软件可以轻松地帮助玩家将福建十...
九分钟了解!手游奇迹陕西辅助工... 九分钟了解!手游奇迹陕西辅助工具!果然一直都是有辅助方法(真实有挂)-哔哩哔哩该软件可以轻松地帮助玩...
第5分钟了解!微信海豚大厅辅助... 第5分钟了解!微信海豚大厅辅助!总是一直总是有辅助软件(证实有挂)-哔哩哔哩该软件可以轻松地帮助玩家...
七分钟了解!创思维激k必胜辅助... 七分钟了解!创思维激k必胜辅助!真是真的是有辅助脚本(有挂方式)-哔哩哔哩;1、玩家可以在创思维激k...
第六分钟了解!悟空大厅辅助助手... 第六分钟了解!悟空大厅辅助助手下载安装!竟然是真的有辅助攻略(有挂规律)-哔哩哔哩进入游戏-大厅左侧...
两分钟了解!竹间茶馆辅助!本来... 两分钟了解!竹间茶馆辅助!本来是有辅助攻略(真实有挂)-哔哩哔哩1、用户打开应用后不用登录就可以直接...
2分钟了解!友友联盟辅助器!竟... 2分钟了解!友友联盟辅助器!竟然存在有辅助工具(有挂攻略)-哔哩哔哩1、每一步都需要思考,不同水平的...
第8分钟了解!518互娱辅助器... 第8分钟了解!518互娱辅助器下载!都是是真的有辅助工具(确实有挂)-哔哩哔哩518互娱辅助器下载透...