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

相关内容

热门资讯

透视规律"hhpok... 透视规律"hhpoker辅助软件是真的么"wepoker的辅助器(原来真的是有辅助平台)-哔哩哔哩;...
透视神器"fishp... 透视神器"fishpoker透视底牌"wepoker有没有机器人(一直真的是有辅助app)-哔哩哔哩...
连日来"智星德州插件... 连日来"智星德州插件2024最新版"wepoker有没有机器人(一直真的是有辅助工具)-哔哩哔哩1、...
透视黑科技"fish... 透视黑科技"fishpoker透视底牌"wepoker底牌透视(果然真的有辅助工具)-哔哩哔哩1、f...
无独有偶"wepok... 无独有偶"wepoker辅助器安装包定制"aapoker透视脚本(真是是真的辅助平台)-哔哩哔哩we...
透视软件"wepok... 您好,wepoker如何设置透视这款游戏可以开挂的,确实是有挂的,需要了解加去威信【13670430...
于此同时"aapok... 于此同时"aapoker怎么设置抽水"wpk辅助(一直真的是有辅助工具)-哔哩哔哩aapoker怎么...
透视透视"werpl... 透视透视"werplan脚本"hhpoker哪个俱乐部靠谱(果然真的有辅助插件)-哔哩哔哩运hhpo...
透视好牌"wepok... 透视好牌"wepoker透视有没有"wepoker私人局开挂视频(好像是有辅助平台)-哔哩哔哩1、w...
围绕透视问题"哈糖大... 围绕透视问题"哈糖大菠萝破解器"aapoker辅助器是真的吗(本来真的有辅助下载)-哔哩哔哩进入游戏...