无法在setTimeout函数下获取组件变量

时间:2018-10-11 08:19:14

标签: javascript angular angular6

我是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 :(得分:1)

您需要使用lambda表达式:

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

答案 1 :(得分:1)

这是因为在function()中, this 指向函数的上下文。

autosavedraftsolution() {
  setTimeout(() => {
    //here, it is not working and even intellisense is not supporting me here
    console.log(this.draftSolutionForm);
  }, 3000);
}

答案 2 :(得分:1)

 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);


      }
   }

答案 3 :(得分:1)

尝试

  

.bind(this)

setTimeout(function () {
  console.log(this.draftSolutionForm);
}.bind(this), 3000);

答案 4 :(得分:0)

ES6 / 2015箭头函数表达式的语法比函数表达式短,并且没有自己的this

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

或者您可以定义一个变量来访问this(词法范围)

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

Finaly bind方法创建一个新函数,该函数在被调用时将其this关键字设置为所提供的值,并在调用新函数时提供给定的参数序列之前

setTimeout(function () {
  console.log(this.draftSolutionForm);
}.bind(this), 3000);