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

相关内容

热门资讯

热点推荐!wepoker插件功... 热点推荐!wepoker插件功能辅助器(辅助挂)确实是有挂(真的有挂辅助攻略)1)免费钻石:进一步探...
科技通报!来玩app破解(辅助... 科技通报!来玩app破解(辅助挂)真是存在有挂(有挂秘笈辅助器)1)辅助插件:进一步探索辅助大陆,与...
今日重大通报!德普之星有辅助软... 今日重大通报!德普之星有辅助软件吗(辅助挂)确实真的有挂(有挂秘籍辅助器)1、点击下载安装,脚本分类...
推荐一款!德州局透视脚本免费版... 推荐一款!德州局透视脚本免费版下载手机版(辅助挂)本来是有挂(有挂教程辅助教程)1、首先打开辅助器下...
一分钟了解!智星德州插件怎么下... 一分钟了解!智星德州插件怎么下载(辅助挂)竟然真的有挂(有挂教学辅助工具);1、金币登录送、破产送、...
重大发现!wepoker插件下... 重大发现!wepoker插件下载(辅助挂)果然存在有挂(有挂细节辅助app)能透视中分为三种模型:模...
热点推荐!拱趴游戏破解器(辅助... 热点推荐!拱趴游戏破解器(辅助挂)真是真的有挂(有挂方法辅助方法)1、有没有辅助教程、有透视吗等服务...
信息共享!wpk辅助(辅助挂)... 信息共享!wpk辅助(辅助挂)一贯有挂(真的有挂辅助工具)是不是有人用挂微扑克wpk插件教程:1、微...
一分钟揭秘!wepoker透视... 一分钟揭秘!wepoker透视破解版(辅助挂)竟然是有挂(有挂工具辅助工具)1、下载好脚本下载之后点...
盘点十款!hhpoker有后台... 盘点十款!hhpoker有后台操作吗(辅助挂)切实真的有挂(有挂方法辅助app)1、辅助软件下载优化...