Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 在构造函数中给定值后未定义的变量?_Angular_Typescript - Fatal编程技术网

Angular 在构造函数中给定值后未定义的变量?

Angular 在构造函数中给定值后未定义的变量?,angular,typescript,Angular,Typescript,我在访问构造函数中使用的变量时遇到问题。您可以看到,currentLang获取值,并且值也在构造函数之外,但是当流转到displayIndustries函数/方法为未定义时,此变量的作用域是否出错因为我尝试使用布尔值,现在字符串仍然未定义您没有在构造函数中使用变量。您正在订阅回调中使用它,该回调在构造函数调用之后/期间异步调用。要防止未定义currentLang,可以对其进行初始化 currentLang = '' constructor( private fb: For

我在访问构造函数中使用的变量时遇到问题。您可以看到,currentLang获取值,并且值也在构造函数之外,但是当流转到
displayIndustries
函数/方法为
未定义时,此变量的作用域是否出错因为我尝试使用
布尔值
,现在字符串仍然
未定义

您没有在构造函数中使用变量。您正在订阅回调中使用它,该回调在构造函数调用之后/期间异步调用。要防止未定义
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;
  } 

(我还使您的代码简洁)

看看代码,一切似乎都很好。你能在Stackblitz之类的东西上重现这个吗?你有没有声明
currentLang
在类内,在构造函数之外
行业
是未定义的,而不是
这个.currentLang
控制台.log(JSON.stringify(this.currentLang))中将.currentLang
赋值给
lang
后得到了什么
您是否在其他任何地方调用
displayIndustries