use*_*173 6 javascript jquery typescript angular
我在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);
});
}
Run Code Online (Sandbox Code Playgroud)
这会给我一个错误,即参数未定义.我想这是因为我使用this.我还可以做些什么?
gel*_*181 21
您需要使用箭头函数表达式(() => {})来保持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);
});
}
Run Code Online (Sandbox Code Playgroud)
当您将回调作为常规旧函数传递时,JavaScript不会将您的回调视为在调用函数的范围内,从而this无法从您认为自己所在的范围调用数据.通过使用箭头函数,范围已保存,this可用于按预期访问数据.