【问题标题】:How to get array json instead of object json如何获取数组 json 而不是对象 json
【发布时间】: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


    【解决方案1】:

    在您的服务中尝试使用:from 而不是 of。检查这个docs

    这是基于您的代码的有效stackblitz

    【讨论】:

      猜你喜欢
      • 2017-12-16
      • 2012-08-26
      • 2020-08-03
      • 2021-06-14
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多