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、首先打开约局吧能不能开挂辅助器下...
透视策略!佛手大菠萝有挂吗(透... 您好,佛手大菠萝有挂吗这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩...
透视手册!wepoker怎么挂... 透视手册!wepoker怎么挂底牌(透视)竟然存在有辅助辅助器(哔哩哔哩)1、许多玩家不知道wepo...
透视经验!wepoker透视脚... 透视经验!wepoker透视脚本安卓(透视)好像有辅助app(哔哩哔哩)wepoker透视脚本安卓破...
透视法子!wepoker游戏的... 透视法子!wepoker游戏的安装教程(透视)好像真的有辅助安装(哔哩哔哩)1)wepoker游戏的...
透视方式!hhpoker一直输... 透视方式!hhpoker一直输有挂吗(透视)果然真的是有辅助插件(哔哩哔哩)1、hhpoker一直输...
透视指南书!德州私人局脚本(透... 透视指南书!德州私人局脚本(透视)原来真的是有辅助安装(哔哩哔哩)1、点击下载安装,德州私人局脚本脚...
透视指南书!wepoker究竟... 透视指南书!wepoker究竟有没有透视(透视)本来真的是有辅助平台(哔哩哔哩)1、完成wepoke...
透视指引!wepoker免费钻... 透视指引!wepoker免费钻石(透视)确实是真的辅助安装(哔哩哔哩)暗藏猫腻,小编详细说明wepo...
透视秘籍!pokemmo手机脚... 透视秘籍!pokemmo手机脚本辅助器(透视)都是存在有辅助神器(哔哩哔哩);1、让任何用户在无需p...