angular - 在构造函数中给出值后未定义的变量?
问题描述
我在访问我在构造函数中使用的变量时遇到问题,this.currentLang
因为您可以看到它取值并且该值也在构造函数之外,但是当流程转到displayIndustries
函数/方法时undefined
,范围内是否有任何问题这个变量导致我尝试使用boolean
,现在仍然使用字符串undefined
。
解决方案
您没有在构造函数中使用变量。您在构造函数调用之后/期间异步调用的订阅回调中使用它。为防止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;
}
(我也让你的代码简洁)
推荐阅读
- node.js - 在 websockets 和 node/express 中创建路由
- c# - 模型未找到 GetEnumerator
- javascript - 更改javascript上的格式消息
- html - 如何修复 Angular 材质不起作用的错误
- visual-studio - 无需编译即可构建 Visual Studio 解决方案
- python - 使用 pandas 重新分配项目会产生错误的结果
- javascript - amCharts 地图在页面刷新时未加载圆圈
- python - 如何更改、添加或删除标签的属性
- python - Python:如何从数组中提取值的第一个实例并将其存储在列表中?
- javascript - 从 iid.google api 获取时从 google apis 没有响应时使用 firebase 云消息传递为 web