在 Angular 组件中使用下划线

问题描述

这是我正在使用的组件的简化版本:

things: Things[] = [...]

addThing(thing: Thing) {
  // when using this.things => 'this' undefined!
}

addThings(things: Thing[]) {
  _.each(things,this.addThing);
}

简而言之,我调用 addThings,它有时会为每个个体 addThing 调用 thing。我究竟做错了什么?为什么 this undefinedaddThing 中?

我以通常的方式(我认为是)安装了下划线:

npm install --save-dev @types/underscore
npm install --save underscore
// angular.json:
"scripts": [
  ...,"node_modules/underscore/underscore-min.js"
]

解决方法

您可以像这样向 this 提供 _.each 上下文:

_.each(things,this.addThing,this);

或者您可以使用自动绑定 this 的箭头函数:

_.each(things,t => this.addThing(t));
,

另一种选择:使 addThing 成为一个单独的箭头函数:

addThing = (thing: Thing) => {
  // here we access the lexical `this`
}