qz 未定义 qz_tray

qz is not defined qz_tray

我一直在寻找一种在客户端从 Web 打印的解决方案(https://medium.com/@yehandjoe/angular-2-raw-printing-service-56614d358754)这就是我一直关注的,它建议使用 qz 托盘来访问打印机。 我已经按原样复制了代码,但它不起作用。

每当执行函数 getprinters() 时,它都会显示 "qz is not defined"

我已经使用这些 npm 命令导入了包

npm 安装 qz-tray sha ws

npm install rsvp,这是我的打印机服务代码:

import { Injectable } from '@angular/core';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/map';


declare var qz: any;
@Injectable()
export class PrinterService {
constructor() { }

errorHandler(error: any): Observable<any> {
    return Observable.throw(error);
}

// Get list of printers connected
getPrinters(): Observable<string[]> {
    return Observable
        .fromPromise(qz.websocket.connect().then(() => qz.printers.find()))
        .map((printers: string[]) => printers)
        .catch(this.errorHandler);
}

// Get the SPECIFIC connected printer
getPrinter(printerName: string): Observable<string> {
    return Observable
        .fromPromise(qz.websocket.connect().then(() => qz.printers.find(printerName)))
        .map((printer: string) => printer)
        .catch(this.errorHandler);
}

// Print data to chosen printer
printData(printer: string, data: any): Observable<any> {
    // Create a default config for the found printer
    const config = qz.configs.create(printer);
    return Observable.fromPromise(qz.print(config, data))
        .map((anything: any) => anything)
        .catch(this.errorHandler);
}

// Disconnect QZ Tray from the browser
removePrinter(): void {
    qz.websocket.disconnect();
}

}

如果我做错了,请指正,否则我将不胜感激任何其他替代解决方案

尝试在构造函数中或之前声明它,你在服务声明之前变量class,它看不到变量

您似乎需要将 qz 托盘导入您的供应商。

我使用 SHA.js: https://www.npmjs.com/package/sha.js 进行加密并使用本机承诺。

所以我在现有导入文件下方的文件顶部添加了以下行:

import * as shajs from 'sha.js';
import * as qz from 'qz-tray';

为 QZ 设置 SHA

记得告诉 QZ 使用新的 sha.js 包:

qz.api.setSha256Type(function (data) {
    return shajs('sha256').update(data).digest('hex')
});

为 QZ 设置原生承诺

记得告诉 QZ 使用新的 sha.js 包:

qz.api.setPromiseType(function (resolver) {
    return new Promise(resolver);
});

我还需要使用此 QZ 服务,它似乎是从 javascript 应用程序与打印机通信的唯一方式。

总之,感谢上面的回答和一些文章,我成功地制作了一个小的angular 7 应用程序, 可以轻松连接verry打印机。

我想分享这段代码,以防万一有人不得不去同样的过程。看起来这是唯一的 post QZ Tray。 首先,您应该通过执行以下命令来安装必要的依赖项:

npm install qz-tray js-sha256 rsvp --save

其次,你应该创建一个打印服务, 这是它的代码:

import { Injectable } from '@angular/core';
import { from as fromPromise, Observable, throwError } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { catchError, map } from 'rxjs/operators';

import * as qz from 'qz-tray';
import { sha256 } from 'js-sha256';

@Injectable({
  providedIn: 'root'
})
export class PrinterService {

  //npm install qz-tray js-sha256 rsvp --save
  constructor() {
    qz.api.setSha256Type(data => sha256(data));
    qz.api.setPromiseType(resolver => new Promise(resolver));
  }
  // Get the list of printers connected
  getPrinters(): Observable<string[]> {
    console.log('+++++++++PrinterService+++++');
    return fromPromise(
      qz.websocket.connect().then(() => qz.printers.find())
    )
    map((printers: string[]) => printers)
      , catchError(this.errorHandler);
  }

  // Get the SPECIFIC connected printer
  getPrinter(printerName: string): Observable<string> {
    return fromPromise(
      qz.websocket.connect()
        .then(() => qz.printers.find(printerName))
    )
    map((printer: string) => printer)
      , catchError(this.errorHandler);
  }

  // Print data to chosen printer
  printData(printer: string, data: any): Observable<any> {
    const config = qz.configs.create(printer);

    return fromPromise(qz.print(config, data))
    map((anything: any) => anything)
      , catchError(this.errorHandler);
  }

  private errorHandler(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.log(error.error);
      console.log('An error occurred:', error.status);
      return throwError(error.error);
    } else {
      console.log('An error occurred:', error.status);
      console.log(error.error);
      return throwError(error.error);
    }
  };
}

最后,你应该只从某个组件调用你的服务,并执行功能,在这种情况下,我使用了应用程序组件:

import { Component } from '@angular/core';
import { PrinterService } from './printer.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'qz-tray-example';
  printers: string[];

  constructor(public _printerService: PrinterService) {

  }

  ngOnInit() {
    this.printers = [];
    console.log('AppComponent____________');
    this._printerService.getPrinters().subscribe(
      data => {
        console.log(data);
        // this.printers = data;
        this.print();
      },
      err => {
        console.log(err);
      }
    );
  }

  print() {



    let content1 = `
    <html>
        <head>
            <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        </head>

        <body>
            <div> 
                <h3>Printing Test 1</h3>
            </div>
        </body>
    </html>`;

    let content2 = `
    <html>
        <head>
            <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        </head>

        <body>
            <div> 
                <h3>Printing Test 2</h3>
            </div>
        </body>
    </html>`;
    var data = [{
      type: 'html',
      format: 'plain', // or 'plain' if the data is raw HTML
      data: content1
    },
    {
      type: 'html',
      format: 'plain', // or 'plain' if the data is raw HTML
      data: content2
    }];
    data[0].data = content1;
    this._printerService.printData('zebra', data).subscribe(
      data => {
        console.log('ok print');
      },
      err => {
        console.log(err);
      }
    );
  }
}

希望这个回答能帮助某人开始使用他的应用程序,祝你好运;)。