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

相关内容

热门资讯

推荐一款!智星德州插件,wep... 推荐一款!智星德州插件,wepoker好友房开挂,好像有挂(有挂辅助)1. 选牌创建新账号,点击进入...
一分钟揭秘!wpk模拟器多开,... 一分钟揭秘!wpk模拟器多开,德普之星辅助器,竟然有挂(有挂攻略)1、德普之星辅助器破解器简单,德普...
玩家必用!德普之星辅助工具如何... 玩家必用!德普之星辅助工具如何打开,德州透视插件,都是是真的有挂(有挂方针)1、完成有辅助插件,帮助...
玩家必用!德州局透视脚本免费版... 玩家必用!德州局透视脚本免费版下载手机版,德州机器人代打脚本,切实是真的有挂(有挂分享)1、让任何用...
最新研发!hhpoker可以开... 最新研发!hhpoker可以开挂吗,wepoker祈福有用吗,真是存在有挂(有挂教程)1、下载好正确...
热点推荐!werplan免费挂... 热点推荐!werplan免费挂下载,红龙poker辅助器免费观看,原来存在有挂(有挂猫腻)1、完成辅...
一分钟教你!aa poker辅... 一分钟教你!aa poker辅助包,pokeplus脚本,真是真的有挂(有挂技巧)1、用户打开应用后...
交流学习经验!wepoker破... 交流学习经验!wepoker破解器,pokemmo辅助器,都是真的是有挂(有挂教程)1、打开软件启动...
玩家科普!werplan外挂,... 玩家科普!werplan外挂,uupoker有透视吗,总是真的是有挂(有挂秘诀)1、下载好正确养号方...
盘点一款!德普之星透视辅助软件... 盘点一款!德普之星透视辅助软件,德扑之心免费透视,总是是有挂(有挂工具)暗藏猫腻,小编详细说明破解器...