我在我的 angular2 项目中使用 jQuery 来做一些事情。但是我无法设法使用我在 angular2 中声明的变量在 jQuery 中使用。我有这样的东西:
export class AddExerciseComponent implements OnInit {
parameters:Array<string> = ["FU"];
constructor() { }
ngOnInit() {
$('.chips').on('chip.add', function(e, chip){
this.parameters.push(chip.data);
console.log(this.selectedValue);
});
}
这会给我一个参数未定义的错误。我想这是因为我使用了 this
。我还能做什么?
最佳答案
您需要使用箭头函数表达式 (() => {}
) 将this
保持在范围内。尝试:
export class AddExerciseComponent implements OnInit {
parameters:Array<string> = ["FU"];
constructor() { }
ngOnInit() {
// removed function keyword and added () => {} syntax
$('.chips').on('chip.add', (e, chip) => {
this.parameters.push(chip.data);
console.log(this.selectedValue);
});
}
当您将回调作为常规旧函数传递时,JavaScript 不会将您的回调视为在调用函数的范围内,从而使 this
无法用于从您认为的范围内调用数据在。通过使用箭头函数,范围被保存并且 this
可用于按预期访问数据。
关于javascript - 在 jquery 中访问 angular2 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39753505/