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、让任何用户在无需微乐自...
今日百科!微乐家乡麻将自建房辅... 今日百科!微乐家乡麻将自建房辅助app,微乐自建房脚本免费入口(开挂自建房)技巧今日百科!微乐家乡麻...
最新通报!微乐自建房辅助工具插... 最新通报!微乐自建房辅助工具插件,微乐自建房脚本免费入口(开挂自建房)教程一、微乐自建房辅助工具插件...
玩家必看秘籍!微乐小程序麻将自... 玩家必看秘籍!微乐小程序麻将自建房辅助工具插件,微乐小程序免费黑科技(开挂自建房)软件1、超多福利:...
记者发布!微乐家乡麻将自建房辅... 记者发布!微乐家乡麻将自建房辅助app,微乐自建房脚本免费入口(开挂自建房)攻略1)微乐家乡麻将自建...
科技通报!微乐微信自建房辅助工... 科技通报!微乐微信自建房辅助工具插件,微乐家乡麻将自建房辅助app(开挂自建房)攻略微乐微信自建房辅...
分享实测!微乐自建房辅助工具脚... 分享实测!微乐自建房辅助工具脚本,微乐自建房脚本免费入口(开挂自建房)工具进入游戏-大厅左侧-新手福...
今日公布!微乐自建房辅助工具脚... 今日公布!微乐自建房辅助工具脚本,微乐家乡麻将自建房辅助app(开挂自建房)教程1)微乐家乡麻将自建...
总算了解!微乐小程序自建房辅助... 总算了解!微乐小程序自建房辅助工具插件,微乐小程序免费黑科技(开挂自建房)插件1、微乐小程序自建房辅...
玩家必看秘籍!微乐小程序自建房... 玩家必看秘籍!微乐小程序自建房辅助工具插件,微乐家乡麻将自建房辅助app(开挂自建房)工具;1、首先...