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

相关内容

热门资讯

总算了解!德州圈脚本,hhpo... 1、总算了解!德州圈脚本,hhpoker德州机器人,曝光教程(有挂透明)。2、hhpoker德州机器...
重大来袭!德州透视是真的假的,... 重大来袭!德州透视是真的假的,hhpoker可以开挂吗,解说技巧(有挂透视)1、玩家可以在德州透视是...
发现一款!impoker辅助,... 发现一款!impoker辅助,来玩德州破解器,微扑克教程(有挂教程)是由北京得来玩德州破解器黑科技有...
指导大家!hhpoker有没有... 指导大家!hhpoker有没有作弊挂,agpoker辅助,wpk教程(有挂教程)1、不需要AI权限,...
玩家必知教程!德普之星透视辅助... 玩家必知教程!德普之星透视辅助软件激活码,wepoker透视脚本,教你教程(有挂教程);玩家必备必赢...
每日必看!wepoker透视底... 每日必看!wepoker透视底牌脚本,hhpoker底牌透视脚本,安装教程(有挂技巧);《WPK辅助...
玩家必看教程!德州局hhpok... 玩家必看教程!德州局hhpoker,WePoKer辅助器,黑科技教程(有挂透明)1、点击下载安装,微...
技巧知识分享!wepoker有... 您好,wepoker有没有透视方法这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302...
盘点十款!大菠萝辅助器,hhp... 自定义hhpoker辅助软件下载系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅...
最新通报!wepoker怎么设... 最新通报!wepoker怎么设置透视,德扑圈有透视吗,细节揭秘(有挂软件);实战中需综合运用上述技巧...