使用 ng-select 时无法读取 null 的属性“$ngoptionlabel”

Tim*_*Tim 6 angular-ngselect angular

我正在使用ng-select显示我的应用程序从 API 检索到的数据,但尽管数据已成功检索到,但下拉列表中并未显示任何内容。它只是说“未找到任何项目”。在控制台中,我有以下错误:

ERROR TypeError: Cannot read property '$ngoptionlabel' of null

这是我的打字稿代码:

// in a service, using HttpClient
this.http.get<string[]>(url);
Run Code Online (Sandbox Code Playgroud)
// in a component, using the service injected in
data: string[] = [];
this.service.get()
   .subscribe(data => {
      this.data = data; // data contains values as expected
      // other logic
   });
Run Code Online (Sandbox Code Playgroud)

在我的模板中,我传递this.datang-select.

<ng-select [items]="data"
           [multiple]="true"
           [closeOnSelect]="false"
           [searchable]="true">
</ng-select>
Run Code Online (Sandbox Code Playgroud)

我认为错误听起来可能与bindLabel选项有关,但我没有使用它。错误是什么意思,我该如何解决?

Tim*_*Tim 6

该错误意味着正在显示的数组中的一项是null。要解决此问题,请null在将 s 传递给 之前将其从数组中过滤掉ng-select。在从 API 检索数据的情况下,您可以使用 rxjsmap运算符来实现这一点。

this.http
   .get<string[]>(url)
   .pipe(
      map(data => data.filter(x => x != null))
   );
Run Code Online (Sandbox Code Playgroud)