Angular调用API动态JSON数据实现MatAutocomplete无报错返回空数组
Angular自动补全返回空数组问题修复方案
已知问题&修复方案
1. 模板DOM结构错误
当前mat-option嵌套错误,加载状态选项被放在循环选项内部,属于无效结构,会导致渲染异常。
修复后component.html代码:
<label class="label" for="company">Publication</label> <input matInput placeholder="" class="input-text js-input" [matAutocomplete]="auto" [formControl]="searchPublicationCtrl"> <mat-autocomplete #auto="matAutocomplete"> <!-- 加载项移到外层作为autocomplete直接子节点 --> <mat-option *ngIf="isLoading" class="is-loading">Loading...</mat-option> <mat-option *ngFor="let publication of filteredPublication" [value]="publication.Title"> <span>{{publication.Title}}</span> </mat-option> </mat-autocomplete>
2. 接口请求参数构造错误
component.ts中POST请求体写为{} + value属于语法错误:对象和字符串拼接会生成无意义的[object Object]xxx内容,后端无法正常接收搜索参数。同时响应取值逻辑错误,给出的API返回结构中不存在Search顶层字段,判断data['Search']永远为undefined,所以一直赋值空数组。
修复后component.ts逻辑代码:
this.searchPublicationCtrl.valueChanges .pipe( debounceTime(500), filter(value => value?.trim().length > 0), // 可选:空输入不发起请求 tap(() => { this.errorMsg = ""; this.filteredPublication = []; this.isLoading = true; }), switchMap(value => // 按后端要求调整请求体字段,示例为传搜索关键词到searchKey字段 this.http.post("http://localhost:3000/articles/publicationData",{searchKey: value}) .pipe( finalize(() => { this.isLoading = false }), ) ) ) .subscribe(data => { // 直接赋值返回的数组,不需要取Search字段 this.filteredPublication = Array.isArray(data) ? data : []; console.log(this.filteredPublication); }, error => { this.isLoading = false; this.errorMsg = "请求失败"; this.filteredPublication = []; });
3. Service请求参数位置错误
service.ts中getPublication方法把headers配置放到了POST的第二个参数(请求体)位置,导致请求头设置失效;且HttpHeaders.set是返回新实例,原写法不会更新headers变量。
修复后service.ts代码:
getPublication(searchKey?: string){ const headers = new HttpHeaders().set('Content-Type', 'application/json'); const url = "http://localhost:3000/articles/publicationData"; // POST参数顺序:url、请求体、配置项 return this.http.post(url, {searchKey}, { headers }); }
修复后可在component中直接调用该service方法,无需硬编码接口地址。
排查建议
如果修复后仍有问题,打开浏览器控制台的「网络」tab,查看该接口的请求参数、响应头和返回内容,确认后端返回的数据结构是否符合预期。
内容的提问来源于stack exchange,提问作者swati goel
相关产品推荐
相关产品推荐

