我有两个全球财产
htmlContentElement
htmlContentContainer
我把它放在
ngAfterViewInit() {
this.htmlContentElement = document.getElementById("messageContent");
this.htmlContentContainer = document.getElementById("messageContainer");
}
我在这种方法中使用这种特性
setOcrMessage() {
let originalContent = this.htmlContentElement.innerHTML;
console.log(this.htmlContentElement);
this.htmlContentElement.innerHTML = this.ocrInfo.message;
if(this.ocrInfo.status) {
this.htmlContentElement.style.color = "#168F48";
this.htmlContentContainer.style.background = "rgb(236, 253, 240)";
} else {
this.htmlContentElement.style.color = "#e50000";
this.htmlContentContainer.style.background = "rgb(251, 233, 235)";
}
setTimeout(function() {
console.log(this.htmlContentElement);
this.htmlContentElement.innerHTML = originalContent;
this.this.htmlContentElement.style.color = "#979797";
this.htmlContentContainer.style.background = "white";
this.htmlContentContainer.style.opacity = "1";
}, 3000);
}
}
第一个console.log(this.htmlContentElement)返回元素
但是setTimeout()中的第二个返回undefined
我在执行setOcrMessage()
constructor( private imageService: ImageService, private documentService: DocumentService,
private ocrService: OcrService) {
this.ocrMessageSubscription = this.ocrService.messageIfOcrCorrectly.subscribe(
(res: ocrMessage) => {
this.ocrInfo = res;
this.setOcrMessage();
}
)
}
为什么htmlContentElement变得未定义?
当我使用
htmlContentElement和
htmlContentContainer
setOcrMessage()中的local属性可以正常工作。
最佳答案
因为您正在丢失使用函数而不是闭包
setTimeout(function() {
console.log(this.htmlContentElement);
this.htmlContentElement.innerHTML = originalContent;
this.this.htmlContentElement.style.color = "#979797";
this.htmlContentContainer.style.background = "white";
this.htmlContentContainer.style.opacity = "1";
}, 3000);
尝试使用箭头功能
setTimeout(() => {
console.log(this.htmlContentElement);
this.htmlContentElement.innerHTML = originalContent;
this.this.htmlContentElement.style.color = "#979797";
this.htmlContentContainer.style.background = "white";
this.htmlContentContainer.style.opacity = "1";
}, 3000);