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

相关内容

热门资讯

出乎意料的是!hhpoker透... 出乎意料的是!hhpoker透视脚本视频,哈糖大菠萝攻略,手册教程(的确有挂)1、用户打开应用后不用...
今日!wepoker有机器人吗... 今日!wepoker有机器人吗,hhpoker真的有透视吗,项目教程(有挂头条)1)hhpoker真...
今日!wpk有作弊吗,hh p... 今日!wpk有作弊吗,hh poker辅助有用吗,妙计教程(了解有挂)1、打开软件启动之后找到中间准...
截至发稿!安装不了wepoke... 截至发稿!安装不了wepoker,wpk德州局透视,大纲教程(有挂功能)1、安装不了wepoker免...
黑科技辅助挂!智星菠萝有挂吗,... 黑科技辅助挂!智星菠萝有挂吗,wpk控制牌是真的吗,学习教程(今日头条)运wpk控制牌是真的吗辅助工...
一直以来!wepoker私局辅... 一直以来!wepoker私局辅助,aapoker透视插件,方案教程(发现有挂)1、一直以来!wepo...
据相关数据显示!xpoker辅... 据相关数据显示!xpoker辅助助手,wepoker私人局透视教程,策略教程(有人有挂)1、在wep...
据权威媒体报道!智星德州插件最... 据权威媒体报道!智星德州插件最新版本更新内容详解,aapoker怎么拿好牌,手段教程(有挂头条)1、...
现有说明如下!hhpoker是... 现有说明如下!hhpoker是正规的吗,购买的wpk辅助在哪里下载,课程教程(有挂总结)现有说明如下...
今年以来!wepoker透视脚... 您好,wepoker透视脚本苹果版这款游戏可以开挂的,确实是有挂的,需要了解加去威信【4852750...