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

相关内容

热门资讯

必知教程!aapoker辅助挂... 必知教程!aapoker辅助挂多功能透视工具,好像是真的有挂(新版有挂)必知教程!aapoker辅助...
推荐十款!aapoker辅助挂... 推荐十款!aapoker辅助挂多功能透视工具,竟然真的是有挂(有挂功能)1、点击下载安装,aapok...
让我来分享经验!aapoker... 让我来分享经验!aapoker辅助挂多功能透视工具,都是真的是有挂(揭秘有挂)aapoker破解侠是...
教程辅助!wepoker辅助挂... 教程辅助!wepoker辅助挂多功能透视工具,都是是真的有挂(有挂秘籍)wepoker脚本下载中分为...
重大推荐!wpk辅助挂多功能透... 重大推荐!wpk辅助挂多功能透视工具,一直是有挂(真的有挂)1、进入游戏-大厅左侧-新手福利-激活码...
2分钟细说!wpk辅助挂多功能... 2分钟细说!wpk辅助挂多功能透视工具,真是真的有挂(有挂解惑)1、2分钟细说!wpk辅助挂多功能透...
玩家必看科普!德普之星辅助挂多... 玩家必看科普!德普之星辅助挂多功能透视工具,果然是有挂(有挂猫腻)1、进入到德普之星是否有挂之后,能...
实测必看!微扑克辅助挂多功能透... 实测必看!微扑克辅助挂多功能透视工具,一贯是真的有挂(有挂工具)1、这是跨平台的微扑克轻量版有透视,...
重大发现!AAPoKer辅助挂... 重大发现!AAPoKer辅助挂多功能透视工具,真是是真的有挂(有挂解惑)AAPoKer破解侠是真的助...
我来向大家传授!智星菠萝德州辅... 我来向大家传授!智星菠萝德州辅助挂多功能透视工具,切实存在有挂(有挂教学)1、智星菠萝德州免费辅助多...