如何获取数组json而不是对象json



我做了一些自动完成功能,它需要一些数组方法。我想使用数组json作为我的API,而不是对象json。

由于filter方法只适用于数组。我必须使用数组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是数组或自动完成功能的工作。

在您的服务中,尝试使用:from而不是of。查看此文档。

这是一个基于您的代码的工作堆栈。

最新更新