не удалось получить переменные компонента в функции setTimeout - PullRequest
0 голосов
/ 11 октября 2018

Я новичок в 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);
      }
   }

Помогите мне определить причину.Спасибо.

Ответы [ 5 ]

0 голосов
/ 11 октября 2018

ES6 / 2015 Синтаксис выражения со стрелкой имеет более короткий синтаксис, чем выражение функции, и не имеет собственного this

setTimeout(() => {
 // this => ConSellerDraftsolSecOneComponent 
 console.log(this.draftSolutionForm);
 }, 3000);

Или вы можете определить переменную для доступа к this (лексическийscope)

let _this = this;
setTimeout(function () {
  console.log(_this.draftSolutionForm);
}, 3000);

Finaly bind метод создает новую функцию, которой при вызове присваивается ключевое слово this с заданным значением, причем заданная последовательность аргументов предшествует любому из предоставленных при вызове новой функции

setTimeout(function () {
  console.log(this.draftSolutionForm);
}.bind(this), 3000);
0 голосов
/ 11 октября 2018

Попробуйте с

.bind (this)

setTimeout(function () {
  console.log(this.draftSolutionForm);
}.bind(this), 3000);
0 голосов
/ 11 октября 2018

Это потому, что внутри функции () это указывает на контекст функции.

autosavedraftsolution() {
  setTimeout(() => {
    //here, it is not working and even intellisense is not supporting me here
    console.log(this.draftSolutionForm);
  }, 3000);
}
0 голосов
/ 11 октября 2018
 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);


      }
   }
0 голосов
/ 11 октября 2018

Вам нужно использовать лямбда-выражение:

setTimeout(() => {
 console.log(this.draftSolutionForm);
    }, 3000);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...