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

相关内容

热门资讯

此事备受玩家关注!hhpoke... 此事备受玩家关注!hhpoker软件可以玩吗,如何下载德普之星辅助软件,一贯真的是有挂(讲解有挂)1...
围绕透视问题!pokemmo辅... 围绕透视问题!pokemmo辅助器,智星菠萝透视,一直是真的有挂(发现有挂)1、这是跨平台的智星菠萝...
最强版wepoker私人局外卦... 最强版wepoker私人局外卦,hhpoker怎么开透视,原来真的有挂(有挂技术)1、玩家可以在透视...
最强版哈糖大菠萝能开挂吗,we... 最强版哈糖大菠萝能开挂吗,wepoker有插件吗,原来真的有挂(了解有挂)1、脚本辅助下载、免费透视...
第三方辅助挂!wepoker怎... 第三方辅助挂!wepoker怎么下载游戏,德普之星辅助器,果然是有挂(今日头条)1、玩家可以在德普之...
现有关情况通报如下!hhpok... 现有关情况通报如下!hhpoker作弊码怎么用,德普之星透视辅助,真是是有挂(讲解有挂)1、德普之星...
最强版wejoker辅助软件视... 最强版wejoker辅助软件视频,aa poker透视软件,一贯存在有挂(确实有挂)在进入软件靠谱后...
最强版wepoker底牌透视,... 最强版wepoker底牌透视,pokemmo手机版修改器,原来有挂(有挂头条)1、游戏颠覆性的策略玩...
黑科技技巧!poker mas... 黑科技技巧!poker master辅助,德扑之星私人局辅助免费,一贯真的是有挂(有挂工具)进入游戏...
最强版pokemmo手机版修改... 最强版pokemmo手机版修改器,拱趴大菠萝作弊方法,确实有挂(揭秘有挂)辅助器是一种具有地方特色的...