ngbTypeahead下拉建议不显示求助:API正常返回但页面卡顿
问题:ngbTypeahead下拉建议不显示,API返回正常但页面卡顿
API已按预期返回响应,但ngbTypeahead组件的下拉建议无法显示,控制台无报错或警告,仅页面卡顿,急需技术协助。
HTML代码
<input id="cust-typeahead-prevent-manual-entry" type="text" [ngClass]="[custSearchingYn == 'Y' ? 'form-control form-control-sm typeahead-loading' : 'form-control form-control-sm']" [(ngModel)]="search.custModel" [inputFormatter]="custFormatter" (selectItem)="customerSelected($event)" [showHint]="true" [resultFormatter]="custFormatter" [editable]='false' [ngbTypeahead]="searchCust" placeholder="Customer Search" />
Angular组件代码
searchCust: OperatorFunction<string, readonly Customer[]> = (text$: Observable<string>) => text$.pipe( debounceTime(200), distinctUntilChanged(), tap(() => (this.custSearchingYn = 'Y')), switchMap((searchCustStr) => searchCustStr.length <= 3 ? [] : this.custService.searchCustomers('QUOTE_SEARCH', searchCustStr). pipe( tap(() => ( this.custSearcFailed = false)), catchError(() => { this.custSearcFailed = true; console.log('Error:'); return of([]); }), ), ), tap(() => (this.custSearchingYn = 'N')) );
API服务代码
searchCustomers(searchContext:string, searchStr: string): Observable<Customer[]> { return this.http.get<Customer[]>(`${environment.apiUrl}/api/customer/list/` + searchContext + `/` + searchStr) .pipe(map((response) => { console.log(JSON.stringify(response)); return response})); }
排查与修复建议
- 核心问题:switchMap返回值类型错误:当搜索字符长度≤3时,直接返回普通数组
[]不符合switchMap要求的Observable类型,会破坏数据流。改成of([])才能保证组件正常接收数据:switchMap((searchCustStr) => searchCustStr.length <= 3 ? of([]) : this.custService.searchCustomers(...)) - 修正状态更新时机:最后一个
tap会在API请求未完成时就把custSearchingYn设为N,导致状态逻辑混乱。将该操作移到API请求的pipe内,确保请求完成后再更新:switchMap((searchCustStr) => searchCustStr.length <=3 ? of([]) : this.custService.searchCustomers(...).pipe( tap(() => (this.custSearchingYn = 'N')), // 移至此处 tap(() => (this.custSearcFailed = false)), catchError(...) )) - 检查数据格式化逻辑:确认
custFormatter函数能正确读取Customer对象的显示字段(如name、id等),若格式化返回空值,下拉会显示为空。 - 调试数据流:在API返回的pipe中添加tap,打印组件实际接收的数据,验证数据是否正确:
tap(data => console.log('组件接收的数据:', data)) - 测试editable属性:暂时移除
[editable]='false',排查该属性是否与输入框交互逻辑冲突导致下拉触发失败。
内容的提问来源于stack exchange,提问作者Phani
相关产品推荐
相关产品推荐

