angular - 打字稿'this'范围问题
问题描述
当我从组件调用 findFromList 函数时,会触发此错误:
错误类型错误:无法在推送时读取未定义的属性“searchInArray”../src/app/shared/services/filter.service.ts.FilterService.searchInObject (filter.service.ts:40)
这似乎是因为“this”在 searchInObject 函数中不再引用 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;
}
}
解决方案
这是您在 中定义的对象的原因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
它将保持函数的上下文作为类的上下文。
推荐阅读
- javascript - 在 useEffect 挂钩中调用 API 在道具更新时无法正常工作
- java - 从servlet创建和下载excel文件
- java - 如何在 Spring MVC 中使用表单数据构造模型对象?
- swift - 如何在swift中覆盖通用谓词的运算符和(&&)?
- python - 将 while 循环用户输入计算添加到列表中。Python3
- docker - Kubernetes 用于多用户应用程序,每个项目都有特定的隔离资源
- html - CSS图像和文本同时悬停
- r - lintr 键盘快捷键 rstudio
- intershop - INTERSHOP HTTP 服务未启动
- c# - 是否有其他方法可以对单独的列表集合进行分组或合并
并存储列表 到新列表的索引 ?