微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Angular 组件中使用下划线

如何解决在 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`
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。