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分钟方针!八闽状元郎破解版辅... 1分钟方针!八闽状元郎破解版辅助(外挂)确实是真的有辅助技巧(哔哩哔哩)1、八闽状元郎破解版辅助免费...
第八分钟手段!微乐小程序辅助开... 第八分钟手段!微乐小程序辅助开挂(外挂)其实真的是有辅助教程(哔哩哔哩)1、微乐小程序辅助开挂破解器...
第4分钟项目!黑科技软件大全(... 第4分钟项目!黑科技软件大全(外挂)竟然是真的有辅助软件(哔哩哔哩);1、黑科技软件大全有没有辅助教...
6分钟模块!永胜联盟会封号吗(... 6分钟模块!永胜联盟会封号吗(外挂)切实真的是有辅助工具(哔哩哔哩)1、永胜联盟会封号吗有没有辅助教...
一分钟法子!青橙竞技辅助器怎么... 一分钟法子!青橙竞技辅助器怎么安装(外挂)好像存在有辅助脚本(哔哩哔哩)青橙竞技辅助器怎么安装能透视...
第八分钟要领!雀友会鱼虾蟹下载... 第八分钟要领!雀友会鱼虾蟹下载官网辅助器(外挂)原来有辅助教程(哔哩哔哩)一、雀友会鱼虾蟹下载官网辅...
第6分钟手筋!小程序跑得快的辅... 第6分钟手筋!小程序跑得快的辅助(外挂)总是是真的有辅助脚本(哔哩哔哩)1、上手简单,内置详细流程视...
第十分钟练习!陕西辅助(外挂)... 第十分钟练习!陕西辅助(外挂)竟然真的有辅助脚本(哔哩哔哩)1、实时陕西辅助透视辅助更新:用户可以随...
2分钟步骤!土豪辅助(外挂)都... 2分钟步骤!土豪辅助(外挂)都是存在有辅助攻略(哔哩哔哩)1、土豪辅助免费脚本咨询教程、土豪辅助免费...
五分钟积累!微信小程序家乡大贰... 五分钟积累!微信小程序家乡大贰破解版(外挂)原来存在有辅助技巧(哔哩哔哩)1、微信小程序家乡大贰破解...