Проблема привязки данных к начальной загрузке NG в Angular из веб-API - PullRequest
0 голосов
/ 19 марта 2019

Я использую функцию typehahead в NG-Bootstrap.Мои данные поступают из веб-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 следующим образом:

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 голосов
/ 19 марта 2019

Похоже, вы применяете метод 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)
});
...