Angular Material Autocomplete遍历Observable报错问题求助
修复Angular Material Autocomplete中keyvalue管道的类型错误
错误原因
你遇到的类型错误是因为keyvalue管道默认期望处理ReadonlyMap、数组或可迭代结构,但你的currencies是Record<string, string>类型的普通对象,TypeScript的类型检查无法将普通对象直接匹配到keyvalue的参数类型要求。
修复方案
方案一:给keyvalue管道添加类型提示函数
修改模板中的*ngFor部分,添加一个自定义标识函数帮助TypeScript识别对象类型:
<ng-container *ngIf="currencies$ | async as currencies"> <mat-form-field appearance="fill"> <mat-label>Currency</mat-label> <input id="currency" type="text" matInput placeholder="Select a currency. E.g. USD" [matAutocomplete]="auto" /> <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete"> <mat-option *ngFor="let currency of currencies | keyvalue:identity" [value]="currency.key"> {{currency.key}} </mat-option> </mat-autocomplete> </mat-form-field> </ng-container>
然后在组件类中新增这个identity函数:
// 组件类中添加 identity = (item: any) => item;
这个函数会让keyvalue管道正确解析普通对象的键值对,绕过类型检查的限制。
方案二:提前将对象转换为键值对数组
直接在数据流中把过滤后的对象转换成数组,避免在模板中依赖keyvalue管道:
修改组件中的currencies$流:
currencies$ = this._currencyService.list().pipe( switchMap((currencies) => { return this.formMain.valueChanges.pipe( startWith(''), map((query) => Object.entries(currencies) .filter(([key]) => key.includes(query.toUpperCase())) .map(([key, value]) => ({ key, value })) // 转换为键值对数组 ) ); }) );
模板中直接遍历数组即可:
<ng-container *ngIf="currencies$ | async as currencies"> <mat-form-field appearance="fill"> <mat-label>Currency</mat-label> <input id="currency" type="text" matInput placeholder="Select a currency. E.g. USD" [matAutocomplete]="auto" /> <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete"> <mat-option *ngFor="let currency of currencies" [value]="currency.key"> {{currency.key}} </mat-option> </mat-autocomplete> </mat-form-field> </ng-container>
这种方式更直观,也彻底避免了keyvalue管道的类型问题。
关于你尝试的错误写法
你之前直接用*ngFor="let currency of currencies$ | keyvalue"时,currencies$是Observable对象,keyvalue管道会遍历Observable自身的内部属性(比如operator、source),而不是它发出的实际数据,所以才会得到错误的键值。必须先用async管道订阅Observable,拿到实际的对象值后再处理。
内容的提问来源于stack exchange,提问作者xRay
相关产品推荐
相关产品推荐

