【发布时间】:2018-10-11 16:41:13
【问题描述】:
我是 Angular(6) 的新手,我遇到了无法在 setTimeout 函数下获取组件变量的问题。看看代码,在那里解释我的问题。
export class ConSellerDraftsolSecOneComponent implements OnInit {
draftSolutionForm: FormGroup;
//Other code
//ngOnIt
ngOnInit() {
this.draftSolutionForm = this.formBuilder.group({
title: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
product: [''],
})
}
//function
autosavedraftsolution() {
//here, it is working
console.log(this.draftSolutionForm);
setTimeout(function () {
//here, it is not working, showing "undefined" and even intellisense is not supporting me here to do this
console.log(this.draftSolutionForm);
}, 3000);
}
}
帮我找出原因。谢谢。
【问题讨论】:
-
尝试使用 lambda 和 setInterval( () => { console.log(this.draftSolutionForm}, 3000);
-
可能是由于箭头功能 ->
var ref= this;和ref.draftSolutionForm将解决您的问题 -
就像@bookboy 指出的那样-
function() {}创建了它自己的范围,因此在它的主体中使用this将引用函数的上下文。要保留原始范围,您应该使用 lambda/箭头函数() => {} -
@ful-stackz 箭头函数也创建了自己的作用域。每个功能都可以。
this不是指scope,而是指context。这些是不同的。箭头函数在创建时绑定到词法范围,您可以通过(function() {}).bind(this)获得类似的结果,但箭头函数是更简洁的表达方式。为了比较,function a() { function b() {} }表示b在a的范围内,您不能在运行时更改它。\ -
@vlaz 感谢您的澄清!我滥用了这些术语,可能会使作者感到困惑,所以感谢您的意见!
标签: javascript angular angular6