首页 > 解决方案 > 在构造函数中给出值后未定义的变量?

问题描述

我在访问我在构造函数中使用的变量时遇到问题,this.currentLang因为您可以看到它取值并且该值也在构造函数之外,但是当流程转到displayIndustries函数/方法时undefined,范围内是否有任何问题这个变量导致我尝试使用boolean,现在仍然使用字符串undefined

标签: angulartypescript

解决方案


您没有在构造函数中使用变量。您在构造函数调用之后/期间异步调用的订阅回调中使用它。为防止currentLang未定义,您可以对其进行初始化。

  currentLang = ''

  constructor(
       private fb: FormBuilder, 
       private langService: LangService ,
       private translate: TranslateService
  ) {

    this.langService.currentLang.subscribe((lang) => {
      this.currentLang = lang;
      this.showCurrentLang = this.currentLang === 'en';
      if (this.AfterDisplayIndustries) {
        this.displayIndustries();
      }
    });
  }


  displayIndustries (industry?: IIndustry) {
    this.AfterDisplayIndustries = true;
    return (this.currentLang === 'en' && industry) ? industry.name : industry.nameCZ;
  } 

(我也让你的代码简洁)


推荐阅读