问题结合数据与Web API的Angular中的NG引导打字



我正在使用ng-bootstrap的Typeahead功能。我的数据来自以下格式的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"
      },
   ]
}

我有一项从IN带来此数据的服务,如下所示:

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

然后将其注入component.ts.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" />

当我尝试使用打字机并且无法正常工作时,我会遇到以下错误。任何帮助都会很棒。

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

看起来您正在将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)
});

最新更新