首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >qz未定义为qz_tray

qz未定义为qz_tray
EN

Stack Overflow用户
提问于 2018-01-10 06:26:33
回答 3查看 3.4K关注 0票数 4

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

每当函数getprinters()被执行时,它都会说"qz未定义“

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

npm安装qz-塔板沙ws

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

代码语言:javascript
复制
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();
}

}

如果我做错了什么,请纠正,否则我会非常感激任何其他的替代解决方案。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-04-23 19:22:24

看起来您需要将qz托盘导入到您的提供商。

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

因此,我在现有导入下面的文件顶部添加了以下行:

代码语言:javascript
复制
import * as shajs from 'sha.js';
import * as qz from 'qz-tray';

QZ的集SHA

请记住告诉QZ使用新的sha.js包如下:

代码语言:javascript
复制
qz.api.setSha256Type(function (data) {
    return shajs('sha256').update(data).digest('hex')
});

集对QZ的本地承诺

请记住告诉QZ使用新的sha.js包如下:

代码语言:javascript
复制
qz.api.setPromiseType(function (resolver) {
    return new Promise(resolver);
});
票数 2
EN

Stack Overflow用户

发布于 2019-03-09 14:45:10

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

总之,多亏了上面的答案和一些文章,我成功地制作了一个小的角7应用程序,它可以很容易地与打印机连接。

我想分享这段代码,以防有人不得不使用相同的程序。看起来这是关于QZ Tray的唯一帖子。首先,您应该通过执行以下命令来安装必要的依赖关系:

代码语言:javascript
复制
npm install qz-tray js-sha256 rsvp --save

其次,您应该创建一个打印服务,下面是它的代码:

代码语言:javascript
复制
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组件:

代码语言:javascript
复制
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);
      }
    );
  }
}

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

票数 1
EN

Stack Overflow用户

发布于 2018-01-10 06:44:58

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48181466

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档