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

相关内容

热门资讯

普及知识!小逸碰胡插件脚本,小... 普及知识!小逸碰胡插件脚本,小旋风辅助器,专业教程(有挂秘笈)-哔哩哔哩;小逸碰胡插件脚本软件透视开...
透视讲解!微信闲来辅助神器,瓜... 透视讲解!微信闲来辅助神器,瓜瓜丰城双剑旧版攻略,透明挂教程!(有挂教学)-哔哩哔哩;瓜瓜丰城双剑旧...
透视有挂!518互游破解,哈糖... 透视有挂!518互游破解,哈糖大菠萝辅助,解密教程(发现有挂)-哔哩哔哩;哈糖大菠萝辅助是一项哈糖大...
科技分享!微信小程序辅助器免费... 科技分享!微信小程序辅助器免费2.0苹果版,闲来辅助神器,实用技巧(有挂讲解)-哔哩哔哩;人气非常高...
技术分享!约局吧辅助辅助外开挂... 技术分享!约局吧辅助辅助外开挂,来趣广西辅助,AA德州教程!(证实有挂)-哔哩哔哩;1、很好的约局吧...
透视工具!随意玩辅助器透视挂,... 透视工具!随意玩辅助器透视挂,四川熊猫辅助软件下载,攻略教程(有挂助手)-哔哩哔哩;AI辅助机器人普...
我来分享!奕乐辅助软件,中至江... 我来分享!奕乐辅助软件,中至江西插件,揭秘教程(证实有挂)-哔哩哔哩;是一款可以让一直输的玩家,快速...
重要通知!花花生活圈怎么挂辅助... 重要通知!花花生活圈怎么挂辅助,决胜辅助,必胜教程(有挂讲解)-哔哩哔哩;相信小伙伴都知道这个花花生...
重磅来袭!中至余干马甲怎么开挂... 重磅来袭!中至余干马甲怎么开挂,九游破解辅助插件教程,必胜教程(有挂总结)-哔哩哔哩;九游破解辅助插...
解密关于!越乡游辅助脚本,开心... 解密关于!越乡游辅助脚本,开心庄园辅助,微扑克教程(有挂方法)-哔哩哔哩;1、很好的越乡游辅助脚本工...