【发布时间】:2020-03-01 04:24:48
【问题描述】:
我做了一些自动完成功能,它需要一些数组方法。我想使用数组 json 作为我的 API 而不是对象 json。
由于过滤方法仅适用于数组。我必须使用数组 json[] 作为我的 API url,但我的 API 是一个对象 json{} 文件。如何使它成为一个数组? 我尝试了一些数组 json API。该代码适用于数组 json,但不适用于对象 json。
HTML:
<mat-autocomplete #auto="matAutocomplete" [displayWith]="getOptionText">
<mat-option *ngFor="let option of (filteredOptions | async)" [value]="option">
{{ option.make }}
</mat-option>
</mat-autocomplete>
服务ts:
@Injectable({
providedIn: 'root'
})
export class Service {
constructor(private http: HttpClient) { }
opts = [];
getData() {
return this.opts.length ?
of(this.opts) :
this.http.get<any>('https://api.myjson.com/bins/15psn9').pipe(map(data => this.opts = data));
}
}
组件 ts:
constructor(private service: Service) { }
ngOnInit() {
this.filteredOptions = this.searchForm.controls['customerId'].valueChanges.pipe(
startWith(''),
debounceTime(100),
switchMap(value => value.length >= 3 ? this.doFilter(value) : [])
);
}
doFilter(value) {
return this.service.getData()
.pipe(
map(response => response.filter((option: { make: { toLowerCase: () => { indexOf: (arg0: any) => number; }; }; }) => {
return option.make.toLowerCase().indexOf(value.toLowerCase()) === 0;
}))
);
}
getOptionText(option) {
return option.make;
}
我预计 API JSON 是数组或自动完成功能有效。
【问题讨论】:
标签: json angular api service format