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

相关内容

热门资讯

总算明白!hhpoker怎么防... 总算明白!hhpoker怎么防作弊,hhpoker到底可以作弊码,真是真的有挂(有挂规律)1、很好的...
教程攻略!aapoker插件,... 教程攻略!aapoker插件,hhpoker软件可以玩吗,一贯真的是有挂(证实有挂)1、在插件功能辅...
玩家必看科普!德普之星透视,n... 玩家必看科普!德普之星透视,newpoker脚本,原来真的是有挂(有挂规律)能透视中分为三种模型:模...
玩家攻略推荐!约局吧是否有挂,... 玩家攻略推荐!约局吧是否有挂,约局吧德州真的有透视挂吗,总是是有挂(有挂透明挂)1)免费钻石:进一步...
实测分享!newpoker怎么... 实测分享!newpoker怎么安装脚本,约局吧德州有挂吗,一贯存在有挂(有挂神器)1、免费脚本咨询教...
大家学习交流!hh poker... 大家学习交流!hh poker辅助有用吗,hhpoker有没有作弊辅助,竟然真的有挂(有挂教程)1、...
玩家必看科普!约局吧德州可以透... 玩家必看科普!约局吧德州可以透视吗,wepoker究竟有没有透视,竟然存在有挂(有挂方法)1、让任何...
今日焦点!wejoker透视方... 今日焦点!wejoker透视方法,pokernow辅助工具,一贯存在有挂(有人有挂)1、辅助软件下载...
关于!破解辅助插件wepoke... 关于!破解辅助插件wepoker,wepoker俱乐部辅助器,都是是有挂(有挂猫腻)1)辅助插件:进...
总算了解!impoker辅助,... 总算了解!impoker辅助,wpk模拟器,竟然有挂(有挂猫腻)透视方法中分为三种模型:靠谱、辅助挂...