window.open() 在 angular 的订阅范围内不工作 2+

window.open() not working under subscribe scope in angular 2+

如果我在订阅范围内调用 this.printInvoice() 方法,它会显示错误 Cannot read 属性 'document' of 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
                       }
                   })
               }

试试这个:

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
           }
       })
   }

刚刚更改了 onload="window.printInvoice();window.close()" 而不是 onload="window.print();window.close()"

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();
           }