qz没有定义qz_tray

问题描述 投票:4回答:3

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

无论何时执行函数getprinters(),它都说“qz未定义”

我使用这些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();
}

}

如果我正在做任何错误,或者我真的很感激任何其他替代解决方案,请更正

typescript angular2-services zebra-printers qz-tray
3个回答
2
投票

看起来您需要将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);
});

0
投票

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


0
投票

我还需要使用这个QZ服务,它看起来是从javascript应用程序与打印机通信的唯一方式。

无论如何,多亏了上面的答案和一些文章,我成功制作了一个小角度7应用程序,女巫轻松连接打印机。

我想分享这段代码,万一有人不得不去同一个过程。看起来这是关于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);
    }
  };
}

最后,你应该从一些组件调用你的服务,并执行这些函数,在这种情况下,我使用了app组件:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.