0

我正在尝试md-autocomplete实现material-2in angular。它假设的工作方式是当用户开始输入时,它会http调用以获取数据并显示在选项中。我能够进行 http 调用,但由于某种原因它不会显示在options.

网页

<md-input-container>
  <input mdInput placeholder="Search drug" [mdAutocomplete]="auto" [formControl]="drug" showPanel="false">
</md-input-container>

<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn">

  <md-option *ngFor="let drug of filteredDrugs | async" [value]="drug.drugname">
    {{ drug.drugname}}
  </md-option>
</md-autocomplete>

TS

export class DialogAutoComplete {
  drug: FormControl;
  drugList = [];
  filteredDrugs: any;

  constructor(public dialogRef: MdDialogRef<DialogAutoComplete>, private getData: GetData) {
    this.drug = new FormControl();
    //this.filteredDrugs = 
    this.filteredDrugs = this.drug.valueChanges.startWith(null)
      .map(drugname => {

        return Array.of(this.getDrugs(drugname)) || [{}];
      });


  }
  getDrugs(val: string) {
    console.log("filterdrugs is called ", val);
    return val ?
      // this.drugList.filter(option => option)
      this.getData.getDataForAutoComplete(val).subscribe(
        (response: Response) => { console.log(response); return response || []; },
        (err) => console.log(err)

      )
      : [{ drugname: "No Such drug found" }];
  }
  displayFn(drug) {
    console.log("displayfn => ", drug);
    return drug == null ? drug : drug.drugname;
  }
}

以下是http电话的回应。

在此处输入图像描述

具有不同 api 调用但类似响应和设置的演示plunker 。笨蛋

感谢帮助。

4

1 回答 1

1

制作filteredDrugs一个可观察的,它以您想要的格式从任何服务(HttpService)获取其数据。

https://blog.bouzekri.net/2016-05-15-angular2-rxjs-simple-paginated-list-with-search-field

您定义的异步*ngFor="let drug of filteredDrugs | async"有助于filterDrugs在运行时获取 的值,因此filteredDrugs需要成为 Observable。

有用的链接:自动完成教程

于 2017-08-02T11:25:53.927 回答