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

相关内容

热门资讯

WPK四人法子!红龙poker... WPK四人法子!红龙poker透视工具,德州微扑克好像是有辅助器技巧1、完成红龙poker透视工具有...
WPK俱乐部妙招!aapoke... WPK俱乐部妙招!aapoker可以开挂吗,德州微扑克好像存在有透视挂教程aapoker可以开挂吗透...
WPK作弊妙计!wepoker... WPK作弊妙计!wepoker破解游戏盒子,德州微扑克本来真的是有透视app小薇(辅助器软件下载)致...
WPK真假法门!aapoker... WPK真假法门!aapoker透视脚本安装包,德州微扑克竟然存在有开挂技巧aapoker透视脚本安装...
WPK辅助器绝活儿!wepok... WPK辅助器绝活儿!wepoker有透视底牌吗,德州微扑克一贯有开挂工具1、wepoker有透视底牌...
WPK私人局法子!wepoke... WPK私人局法子!wepoker软件靠谱么,德州微扑克好像是真的有透视挂插件进入游戏-大厅左侧-新手...
WPK方法课程!wepoker... WPK方法课程!wepoker透视脚本苹果,德州微扑克真是有辅助器脚本1、在wepoker透视脚本苹...
WPK私人局学习!wepoke... 您好,wepoker私人局俱乐部辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704...
WPK工具方案!wepoker... WPK工具方案!wepoker免费透视脚本,德州微扑克果然是有开挂技巧1、wepoker免费透视脚本...
WPK德州局策略!wepoke... 您好,wepoker有辅助工具吗这款游戏可以开挂的,确实是有挂的,需要了解加去威信【13670430...