首页 > 解决方案 > 带有打印操作的 Angular TypeError

问题描述

我编写了一个代码,用户可以从下拉框中选择打印机类型,然后通过单击按钮使用选定的打印机打印内容。每当我单击打印按钮时,它都会给出typeerror如下所示。我搜索了问题并对其进行了初始化,但它不起作用。我应该怎么做才能修复这个错误?

在此处输入图像描述

HTML:

<mat-form-field appearance="outline" fxFlex="100" fxFlex.gt-xs="50" class="w-100-p py-8">
    <mat-label>Printer Name</mat-label>
    <mat-select [(ngModel)]="selectedPrinter" name="selectedPrinter" [compareWith]="comparePrinter" >
        <mat-option *ngFor="let prm of printerList" [value]="prm">
            {{prm.Name}}
        </mat-option>
    </mat-select>
</mat-form-field>
<button mat-button matRipple class="purple-500 fuse-white-fg mr-12" (click)="printSticker()"> Print Sticker </button>

TS:

public _stickerData: IStickerData = {};
    selectedPrinter: IPrinter = {};
        printerList: IPrinter[];
    selection = new SelectionModel<IStickerData>(true, []);
        printSticker() {
            this.confirmDialogRef = this._dialog.open(FuseConfirmDialogComponent, {
                disableClose: false
            });
    
            this.confirmDialogRef.componentInstance.confirmMessage = 'Do you want to print the sticker?';
    
            this.confirmDialogRef.afterClosed().subscribe(result => {
                if (result) {
                    this.selection.selected[0].SelectedPrinter = this.selectedPrinter;
                    this._productionService.printStickerData(this._stickerData).subscribe((response: IStickerData) => {
                        this._stickerData = response;
                        this._messages.Show("Printed", "SUCCESS", 3);
                    });
                }
            });
        }

标签: javascripthtmlangulartypescripttypeerror

解决方案


this.selection.selected[0].SelectedPrinter是空的,您需要使用至少一个对象对其进行初始化,以便访问数组元素及其属性。

selection = new SelectionModel<IStickerData>(true, []);

上面的语句创建了一个类型为空的数组IStickerData,但它是空的。

可能你需要类似的东西:

this.selection.push =new StickerData(this.selectedPrinter);

whereStickerData应该是一个实现 IStickerData 的类,并且必须具有构造函数来传递该字符串并返回一种IStickerData对象类型。

例如:

interface IStickerData{
   SelectedPrinter: string
}

class StickerData implements IStickerData{
   SelectedPrinter = '';
   constructor(item: string){
     this.SelectedPrinter = item;
   }
}

推荐阅读