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

相关内容

热门资讯

开挂透视!pokernow辅助... 开挂透视!pokernow辅助工具,微信微乐辅助ios,阶段教程(有挂技巧)-哔哩哔哩1、进入到po...
了解透视!wpk透视是真的假的... 了解透视!wpk透视是真的假的,微乐自建房脚本下载,机巧教程(存在有挂)-哔哩哔哩在进入wpk透视是...
普及透视!德州透视hhpoke... 普及透视!德州透视hhpoker,微乐小程序免费黑科技在线下载,指南书教程(有挂存在)-哔哩哔哩1、...
分享透视!hhpoker辅助器... 分享透视!hhpoker辅助器视频,微乐四川麻将辅助器,法门教程(有挂分享)-哔哩哔哩hhpoker...
必备透视!pokemmo辅助脚... 必备透视!pokemmo辅助脚本,微乐江苏小程序游戏破解器下载,模板教程(有挂教学)-哔哩哔哩1、每...
解密透视!wepoker辅助软... 解密透视!wepoker辅助软件视频,微乐宁夏小程序插件,讲义教程(有挂辅助)-哔哩哔哩1、在wep...
揭露透视!hhpkoer辅助器... 您好,hhpkoer辅助器这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很...
解迷透视!wepoker透视脚... 解迷透视!wepoker透视脚本下载,微乐自建房辅助工具别人怎么看,积累教程(真的有挂)-哔哩哔哩1...
分享透视!wepoker私局代... 分享透视!wepoker私局代打,微信小程序怎么开挂,手段教程(有挂教学)-哔哩哔哩一、wepoke...
辅助透视!德普之星辅助器,微乐... 辅助透视!德普之星辅助器,微乐春天扑克开挂辅助插件,攻略教程(有挂助手)-哔哩哔哩1、许多玩家不知道...