如何获取Material 2(Angular 4)自动完成功能以搜索外部API

时间:2017-10-22 07:00:44

标签: angular material-design angular-material2

我试图让Angular Material 2自动完成功能来搜索API,而不是按照示例在数组内搜索。这就是我试过的:

HTML:

<mat-form-field fxFlex="33" class="mr-20 mt-20">
  <input matInput placeholder="State" aria-label="State" [matAutocomplete]="auto" [formControl]="stateCtrl">
  <mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let state of filteredStates | async" [value]="state.name">
      <span>{{ state.name }}</span>
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

TS:

this.stateCtrl = new FormControl();
this.filteredStates = this.stateCtrl.valueChanges
  .startWith(null)
  .debounceTime(400)
  .do(value => {
    this.ClientsService.search(value).then( res => {
      console.log(res, 'oi');
      this.states = res;
    })
  });

但是,当我输入时,我收到此错误:Error: Cannot find a differ supporting object 'e' of type 'string'. NgFor only supports binding to Iterables such as Arrays.

请注意e是我在搜索字段中输入的内容。我从服务器获得的响应是​​一个包含对象的数组。

我在这里缺少什么?

2 个答案:

答案 0 :(得分:8)

如果您希望在模板中显示states,那么根据您将传入数据存储到的内容,那就是您要在模板中显示的内容。

所以:

<mat-option *ngFor="let state of states" [value]="state.name">

而不是

<mat-option *ngFor="let state of filteredStates | async" [value]="state.name">

与TS:

this.filteredStates = this.stateCtrl.valueChanges
  .startWith(null)
  .debounceTime(400)
  .do(value => {
    this.ClientsService.search(value).then( res => {
      console.log(res, 'oi');
      this.states = res;
    })
  })
  .subscribe()

带有随机查克诺里斯笑话的傻瓜;)https://stackblitz.com/edit/angular-uu4cya?file=app%2Fapp.component.ts

答案 1 :(得分:1)

您很可能忘记解析从服务器获取的结果。

this.states = JSON.parse(res);

这应解决问题。