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、游戏颠覆性的策略玩法,独创...
有挂透视!红龙poker作必弊... 有挂透视!红龙poker作必弊指令!好像真的有辅助方法(有挂透视)-哔哩哔哩1、打开软件启动之后找到...
了解透视!智星德州插件!总是一... 了解透视!智星德州插件!总是一直总是有辅助脚本(有挂细节)-哔哩哔哩;1、该软件可以轻松地帮助玩家将...
揭露透视!pokerworld... 揭露透视!pokerworld破解版下载!果然真的有辅助攻略(有挂总结)-哔哩哔哩1、完成poker...
分享透视!大菠萝免费辅助器!竟... 分享透视!大菠萝免费辅助器!竟然真的有辅助工具(新版有挂)-哔哩哔哩1、大菠萝免费辅助器破解器简单,...
解迷透视!pokemmo辅助器... 解迷透视!pokemmo辅助器!原来真的有辅助神器(有挂细节)-哔哩哔哩1、每一步都需要思考,不同水...
总结透视!德州圈脚本!一贯存在... 总结透视!德州圈脚本!一贯存在有辅助工具(证实有挂)-哔哩哔哩1、起透看视 德州圈脚本辅助软件价格2...
详情透视!cloudpoker... 详情透视!cloudpoker怎么开挂!一直真的有辅助教程(有挂规律)-哔哩哔哩1、cloudpok...