Select2查询服务为空

时间:2018-06-12 06:56:48

标签: angular typescript scope

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

当我选择下拉列表时,它显示错误TypeError(无法读取属性'machineService'为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);
      }
    );
  }
};
}

有人知道吗?

2 个答案:

答案 0 :(得分:1)

范围问题。

使用胖箭来摆脱它。

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);
        }
      );
    }
  };
}

答案 1 :(得分:0)

使用function () {}时,this关键字将指向函数本身的上下文。由于服务是在外部定义的,因此在此范围内不会知道。在箭头功能之前,你必须这样做;

var that = this;
{
 // ...
 query: function (options) {
    that.machineService.findProjections(options.term).subscribe();
 }
 // ...
}

然而,使用ES6箭头功能(=>),不再需要了。他们使用所谓的词法范围。使用箭头函数时,范围不会更改,因此this仍将引用原始上下文。

query: (options) => this.machineService.findProjections(options.term).subscribe()
相关问题