如果我在subscribe范围内调用this.printInvoice()方法,则会显示错误无法读取属性' document'为null
onSubmit() {
this.ItemSellService.addItemSale(this.item_sale).subscribe(res => {
if (res.success) {
this.printInvoice();
} else {
// fail message
}
})
}
printInvoice(): void {
let printContents, popupWin;
printContents = document.getElementById('print-section').innerHTML;
popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
popupWin.document.open();
popupWin.document.write(`
<html>
<head>
<title>Print tab</title>
<style>
//........Customized style.......
</style>
</head>
<body onload="window.print();window.close()">${printContents}</body>
</html>`
);
popupWin.document.close();
}
但它在订阅范围之外的正常工作形式如下:
onSubmit() {
this.printInvoice();
this.ItemSellService.addItemSale(this.item_sale).subscribe(res => {
if (res.success) {
// I need to call after successful operation
} else {
// fail message
}
})
}
答案 0 :(得分:0)
试试这个:
onSubmit() {
var that = this; // use this context where the function works as expected
this.ItemSellService.addItemSale(this.item_sale).subscribe(res => {
if (res.success) {
that.printInvoice();
} else {
// fail message
}
})
}
答案 1 :(得分:0)
刚改变onload =&#34; window.printInvoice(); window.close()&#34;而不是onload =&#34; window.print(); window.close()&#34;
printInvoice(): void {
let printContents, popupWin;
printContents = document.getElementById('print-section').innerHTML;
popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
popupWin.document.open();
popupWin.document.write(`
<html>
<head>
<title>Print tab</title>
<style>
//........Customized style.......
</style>
</head>
<body onload="window.printInvoice();window.close()">${printContents}</body>
</html>`
);
popupWin.document.close();
}