首页 > 解决方案 > 无法在 setTimeout 函数下获取组件变量

问题描述

我是 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);
      }
   }

帮我找出原因。谢谢你。

标签: javascriptangularangular6

解决方案


您需要使用 lambda 表达式:

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

推荐阅读