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)佛手大菠萝有挂吗免...
开挂透视!智星菠萝有挂吗,微乐... 开挂透视!智星菠萝有挂吗,微乐自建房脚本最新版本更新内容,教程书教程(有人有挂)-哔哩哔哩进入游戏-...
普及透视!wepokerplu... 普及透视!wepokerplus透视脚本免费,微信小程序微乐破解器,要领教程(有挂工具)-哔哩哔哩1...
解谜透视!wepoker开辅助... 解谜透视!wepoker开辅助能查到吗,微信微乐小程序有窍门吗,举措教程(有挂细节)-哔哩哔哩1)w...
推荐透视!佛手在线是不是有挂,... 推荐透视!佛手在线是不是有挂,万能透视辅助器免费版,窍门教程(竟然有挂)-哔哩哔哩1、玩家可以在佛手...
总结透视!wpk辅助器是真的吗... 总结透视!wpk辅助器是真的吗,微乐贵阳麻将辅助,窍门教程(有挂猫腻)-哔哩哔哩1、wpk辅助器是真...
解谜透视!poker worl... 解谜透视!poker world辅助,微乐多乐跑作弊,练习教程(有挂方略)-哔哩哔哩1、poker ...
了解透视!wpk插件,微乐四川... 了解透视!wpk插件,微乐四川小程序修改器,演示教程(了解有挂)-哔哩哔哩1、操作简单,无需wpk插...
开挂透视!hh poker软件... 开挂透视!hh poker软件,微乐陕西小程序破解器,方案教程(证实有挂)-哔哩哔哩1、金币登录送、...
关于透视!aapoker透视脚... 关于透视!aapoker透视脚本下载,微信小程序游戏破解器,积累教程(有人有挂)-哔哩哔哩1、完成a...