首页 > 解决方案 > Select2 查询服务为空

问题描述

我会为我的 select2 下拉菜单自定义搜索。在搜索字段中写入 3 个字符后,我将使用这些搜索参数执行服务调用。

当我选择下拉菜单时,它显示错误 TypeError (Cannot read property 'machineService' of null) 在调用 getSelectOptions-Method 之前初始化服务。

HTML:

<select2 id="inputMachine"
         [data]="machinesModel.data"
         [options]="machinesModel.options"
         [width]="'100%'"
         [disabled]="machinesModel.isDisabled()"
         (valueChanged)="machinesModel.onValueChanged($event); onSelectedMachinesChanged($event)">
</select2>

零件:

protected getSelectOptions(placeholder: string) {
return {
  allowClear: false,
  placeholder: this.translate.instant(placeholder),
  multiple: true,
  minimumInputLength: 3,
  theme: 'bootstrap',
  query: function (options) {
    this.machineService.findProjections(options.term).subscribe(
      machines => {
        this.setMachines(machines);
        options.callback(this.machinesModel.data);
      },
      error => {
        console.log('Could not load machines: ', error);
      }
    );
  }
};
}

有人知道吗?

标签: angulartypescriptscope

解决方案


范围问题。

使用胖箭头摆脱它。

protected getSelectOptions(placeholder: string) {
  return {
    allowClear: false,
    placeholder: this.translate.instant(placeholder),
    multiple: true,
    minimumInputLength: 3,
    theme: 'bootstrap',
    query: (options) => {
      this.machineService.findProjections(options.term).subscribe(
        machines => {
          this.setMachines(machines);
          options.callback(this.machinesModel.data);
        },
        error => {
          console.log('Could not load machines: ', error);
        }
      );
    }
  };
}

推荐阅读