【问题标题】:How to get Material 2 (Angular 4) autocomplete to searching an external API如何让 Material 2 (Angular 4) 自动完成以搜索外部 API
【发布时间】:2018-04-02 22:33:00
【问题描述】:

我正在尝试让 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 是我在搜索字段中输入的内容。我从服务器得到的响应是一个包含对象的数组。

我在这里错过了什么?

【问题讨论】:

  • 你在filteredStates得到值吗
  • 您忘记将从服务器获取的数据解析为 JSON。做一个 JSON.parse() 它应该可以工作
  • @Timothy 我正在解析服务端的数据,所以不是这样。当我再次尝试解析数据时,我得到了同样的错误。
  • @RahulSingh 是的,我确实得到了一个包含对象的数组

标签: angular material-design angular-material2


【解决方案1】:

如果您想在模板中显示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()

随机的 Chuck Norris 笑话 ;) https://stackblitz.com/edit/angular-uu4cya?file=app%2Fapp.component.ts

【讨论】:

  • 当我尝试您的代码时,我收到以下错误:Type 'Subscription' is not assignable to type 'Observable&lt;string[]&gt;'. Property '_isScalar' is missing in type 'Subscription'. Property 'unsubscribe' does not exist on type 'Observable&lt;string[]&gt;'. 您使用的是哪个版本的 Angular?我在 4.4.5 和 Material 2,beta 12
  • 是的,filteredStates 在这种情况下需要是 Subscription 而不是 Observable,所以应该声明为 filteredStates: Subscription; 我认为应该这样做:)
  • 太棒了!很高兴听到! :) :)
  • 最后一个问题是,如何显示对象名称而不是 id?在 html 部分,我已将 [value]="state.name" 更改为 [value]="state.id" ,当我获得 ID 时使用表单值是正确的,但是,这是步进器的一部分,它替换了 id 的名称。
  • 嗯...您可以将value 用作state.id,但在插值中显示您想要的任何内容,在这种情况下,您的跨度中的state.name,对吗?还是我在这里误会了?
【解决方案2】:

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

this.states = JSON.parse(res);

这应该可以解决问题。

【讨论】:

  • 前面评论中提到,数据是在服务端解析的,所以不是这样。我什至尝试过您的建议,但仍然遇到同样的错误。
猜你喜欢
  • 2018-12-12
  • 1970-01-01
  • 1970-01-01
  • 2020-01-11
  • 2018-10-19
  • 1970-01-01
  • 2021-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多