Я новичок в 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);
}
}
Помогите мне определить причину. Спасибо.
Вам нужно использовать выражение лямбда:
setTimeout(() => {
console.log(this.draftSolutionForm);
}, 3000);
Попробуйте
.bind (это)
setTimeout(function () {
console.log(this.draftSolutionForm);
}.bind(this), 3000);
Это связано с тем, что внутри функции() это указывает на контекст функции.
autosavedraftsolution() {
setTimeout(() => {
//here, it is not working and even intellisense is not supporting me here
console.log(this.draftSolutionForm);
}, 3000);
}
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(() => {console.log(this.draftSolutionForm);}, 3000);
}
}
ES6/2015 Выражение функции стрелки имеет более короткий синтаксис, чем выражение функции и не имеет свой собственный this
setTimeout(() => {
// this => ConSellerDraftsolSecOneComponent
console.log(this.draftSolutionForm);
}, 3000);
Или вы можете определить переменную для доступа к this
(лексическая область)
let _this = this;
setTimeout(function () {
console.log(_this.draftSolutionForm);
}, 3000);
Метод finaly bind
создает новую функцию, которая при вызове имеет это ключевое слово, заданное для предоставленного значения, с заданной последовательностью аргументов, предшествующей любому, когда она вызывается при вызове новой функции
setTimeout(function () {
console.log(this.draftSolutionForm);
}.bind(this), 3000);
var ref= this;
иref.draftSolutionForm
решит вашу проблему