打字稿“ this”范围问题

时间:2019-02-18 14:19:51

标签: angular typescript

当我从组件调用findFromList函数时,会触发此错误:

  

错误TypeError:无法读取未定义的属性'searchInArray'       在推送../src/app/shared/services/filter.service.ts.FilterService.searchInObject   (filter.service.ts:40)

这似乎是因为searchInObject函数中的'this'不再引用FilterService。

Angular FilterService代码:

import {Injectable, EventEmitter} from '@angular/core';

@Injectable()
export class FilterService {


  findFromList(list, keyword) {
    return list.filter((el) => this.search(el, keyword));
  }

  search(el, keyword) {
    const type = Array.isArray(el) ? 'array' : typeof el;
    const searchFunc = this.getFuncByType(type);

    return searchFunc(el, keyword);
  }

  getFuncByType(type) {

    const match = {
      'string': this.searchInText,
      'number': this.searchInText,
      'boolean': this.searchInText,
      'array': this.searchInArray,
      'object': this.searchInObject,
    };

    if (typeof match[type] !== 'undefined') {
      return match[type];
    } else {
      throw new Error(`Unknown element type "${type}"`);
    }
  }

  searchInText(text, keyword) {
    return (text.toString().indexOf(keyword) !== -1);
  }

  searchInObject(obj, keyword) {
    return this.searchInArray(Object.values(obj), keyword);
  }

  searchInArray(arr, keyword) {
    return arr.find((el) => this.search(el, keyword)) !== undefined;
  }
}

1 个答案:

答案 0 :(得分:1)

这是您在getFuncByType中定义的对象的原因。它导致this引用该对象而不是FilterService类。将定义更新为:

const match = {
  'string': this.searchInText.bind(this),
  'number': this.searchInText.bind(this),
  'boolean': this.searchInText.bind(this),
  'array': this.searchInArray.bind(this),
  'object': this.searchInObject.bind(this),
};

通过将每个函数绑定到this,它将把函数的上下文保留为类的上下文。

相关问题