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

相关内容

热门资讯

透视教你"wepok... 透视教你"wepoker轻量版透视方法"总是是真的辅助挂(哔哩哔哩)1、进入到wepoker轻量版透...
透视揭幕"wepok... 透视揭幕"wepoker插件功能辅助器"其实是真的辅助技巧(哔哩哔哩)1、操作简单,无需wepoke...
透视开挂"wpk插件... 透视开挂"wpk插件"一直存在有辅助器(哔哩哔哩)1、操作简单,无需wpk插件手机版透视脚本,只需要...
透视解谜"aapok... 透视解谜"aapoker辅助器是真的吗"好像是真的辅助插件(哔哩哔哩)1、首先打开aapoker辅助...
透视揭幕"hhpok... 透视揭幕"hhpoker有后台操控吗"好像是真的辅助技巧(哔哩哔哩)1、起透看视 hhpoker有后...
透视揭幕"wepok... 透视揭幕"wepokerplus辅助"本来有辅助神器(哔哩哔哩)wepokerplus辅助破解侠是真...
透视详细"wepok... 透视详细"wepoker透视有用吗"其实是有辅助攻略(哔哩哔哩)1、打开软件启动之后找到中间准星的标...
透视揭露"pokem... 透视揭露"pokemmo脚本辅助器"好像存在有辅助攻略(哔哩哔哩)1、pokemmo脚本辅助器公共底...
透视解迷"哈糖大菠萝... 透视解迷"哈糖大菠萝万能挂"总是是有辅助技巧(哔哩哔哩)该软件可以轻松地帮助玩家将哈糖大菠萝万能挂外...
透视分享"wepok... 透视分享"wepoker能不能透视"原来有辅助器(哔哩哔哩)1、完成wepoker能不能透视有辅助插...