从Web API将数据绑定到Angular中的NG bootstrap typeahead时遇到问题

时间:2019-03-19 12:18:47

标签: angular ng-bootstrap

我正在使用NG-Bootstrap的预输入功能。我的数据来自Web api,采用以下格式,该格式已从以前的格式更改。旧格式为:

result: Array(749)
[0 … 99]
0: "0000105862"
1: "0000105869"
2: "0000105875"
3: "0000110855"
4: "0000110856"
5: "0000110859"
6: "0000111068"
7: "0000111069"
8: "0000111077"
9: "0000112050"
etc

新格式为:

{  
   "result":[  
      {  
         "graphical":{  
            "link":"https://link.com",
            "value":"82374982374987239487"
         },
         "id":{  
            "link":"https://links.com",
            "value":"39485039485039485093485093"
         },
         "serial_number":"2837492837498237498"
      },
   ]
}

我有一项服务,可从中获取此数据,如下所示:

getSerials(customerId): Observable<any> {
    return this.http.get<any>(this.serialApiUrl + "?customer_id=" + customerId)
      .pipe(
        catchError(this.handleError)
      );
  }

然后将其注入到component.ts中,如下所示:

public si_id = [];

private getSerials() {
  this.service.getSerials(this.customer_id).subscribe((data) => {
    for (var i = 0; i < data['result'].length; i++) {
      this.si_id.push(data['result'][i]);
  }
    console.log('Data' + data);
    this.loading = false;
    console.log('Result - ', data);
    console.log('Serial data is received');
  })
}

ngOnInit() {
    this.getSerials();
    this.serviceForm = new FormGroup({
    customer_id: new FormControl(this.customer_id),
    si_id: new FormControl(this.si_id[0], Validators.required),
});
}

public model: any;

search = (text$: Observable<string>) =>
    text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      map(term => term === '' ? []
        : this.si_id.filter(v => v.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0, 10))
    )

然后在html中输入

<ng-template #rt let-r="result" let-t="term">
   <ngb-highlight [result]="r" [term]="t">here</ngb-highlight>
</ng-template>
<input id="si_id" type="text" placeholder="Serial number" formControlName="si_id" class="form-input"
[ngbTypeahead]="search" [resultTemplate]="rt" />

当我尝试使用TypeAhead且无法正常工作时,出现以下错误。任何帮助都会很棒。

ERROR TypeError: v.toLowerCase is not a function
    at Array.filter (<anonymous>)

1 个答案:

答案 0 :(得分:0)

好像您正在将toLowerCase()方法应用于对象。

search = (text$: Observable<string>) =>
    text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      map(term => term === '' ? []
        : this.si_id.filter(v => v.serial_number.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0, 10))

根据您的结构:

const data = {
  "result": [{
    "graphical": {
      "link": "https://link.com",
      "value": "82374982374987239487"
    },
    "id": {
      "link": "https://links.com",
      "value": "39485039485039485093485093"
    },
    "serial_number": "2837492837498237498"
  }, ]
}

const si_id = [];

// You are looping here.
for (var i = 0; i < data['result'].length; i++) {
  si_id.push(data['result'][i]);
}

// Filter it here
si_id.map(m => {
  console.log(m.serial_number)
});