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

相关内容

热门资讯

今日焦点!青鸟辅助器,wepo... 今日焦点!青鸟辅助器,wepoker黑侠辅助器正版下载,辅助教程(有挂规律);1、很好的青鸟辅助器工...
最新技巧!途游游戏辅助脚本,w... 最新技巧!途游游戏辅助脚本,wepoker透视脚本免费使用视频,线上教程(揭秘有挂);1、超多福利:...
热点推荐!福建天天开心辅助工具... 热点推荐!福建天天开心辅助工具下载,wpk官网下载链接,教你攻略(有挂透明挂);福建天天开心辅助工具...
玩家必知教程!挂机操作微乐,w... 玩家必知教程!挂机操作微乐,wepoker怎么挂底牌,黑科技教程(真的有挂)是一款可以让一直输的玩家...
带你了解!微乐小程序免费黑科技... 带你了解!微乐小程序免费黑科技下载,wepoker私人局辅助器怎么用,德州论坛(确实有挂);人气非常...
大家学习交流!青龙辅助最新下载... 大家学习交流!青龙辅助最新下载,pokeplus脚本,专业教程(有挂教程);青龙辅助最新下载中的10...
教程辅助!楚天游辅助,拱趴大菠... 《教程辅助!楚天游辅助,拱趴大菠萝十三水作弊,黑科技教程(有挂攻略)》 楚天游辅助软件透明挂更新公告...
新手必备!牵手跑得软件,wep... 新手必备!牵手跑得软件,wepoker高级辅助,线上教程(真是有挂)相信很多朋友都在电脑上玩过牵手跑...
传递经验!白金岛跑胡子脚本,微... 传递经验!白金岛跑胡子脚本,微扑克游戏辅助器,玩家教你(真实有挂);最新版2026是一款经典耐玩的益...
科普!陕西辅助,德州透视脚本,... 科普!陕西辅助,德州透视脚本,科技教程(真的有挂)是一款可以让一直输的玩家,快速成为一个“必胜”的a...