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、透视好...
透视有挂!wpk私人辅助,wp... 透视有挂!wpk私人辅助,wpk透视辅助下载,系统教程(竟然存在有挂);1、wpk透视辅助下载ai辅...
透视免费!wepoker脚本下... 透视免费!wepoker脚本下载,本然是真的有挂(透视)插件教程(有挂脚本)1、这是跨平台的wepo...
透视肯定!wpk透视工作室,w... 透视肯定!wpk透视工作室,wpk俱乐部是真的吗,力荐教程(好像真的是有挂);1、进入到wpk俱乐部...
透视有挂!来玩app破解,一贯... 透视有挂!来玩app破解,一贯存在有挂(透视)透明挂教程(有挂方法);1、来玩app破解系统规律教程...
透视好牌!微扑克微乐辅助,wp... 透视好牌!微扑克微乐辅助,wpk模拟器多开,安装教程(真是真的有挂)该软件可以轻松地帮助玩家将微扑克...
辅助透视!wepoker好友助... 辅助透视!wepoker好友助力码,本来真的有挂(透视)解密教程(有挂教程)1、wepoker好友助...
透视脚本!wepoker怎么下... 透视脚本!wepoker怎么下载游戏,往昔存在有挂(透视)2025教程(有挂解密);所有人都在同一条...
透视辅助!wpk透视工作室,w... 透视辅助!wpk透视工作室,wpk插件辅助,透明挂教程(都是有挂)1、wpk透视工作室ai机器人多个...
透视新版!cloudpoker... 透视新版!cloudpoker作弊,本然有挂(透视)科技教程(有挂黑科技)在进入cloudpoker...