typescriptangular2-serviceszebra-printersqz-tray

qz is not defined qz_tray


I have been looking for a solution to print from web on client side this (https://medium.com/@yehandjoe/angular-2-raw-printing-service-56614d358754) is what i have been following it suggests to use qz tray to get access for printer. I have copied the code as it is but its not working.

whenever the function getprinters() is executed it says "qz is not defined"

i have imported packages using these npm commands

npm install qz-tray sha ws

npm install rsvp, this is my printer service code :

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

}

Kindly Correct if i am doing any mistake or i would really appreciate any other alternate solution


Solution

  • It looks like you need to import qz tray to your provider.

    I used SHA.js: https://www.npmjs.com/package/sha.js for encryption and used native promises.

    So I added the following lines to the top of the file below the existing imports:

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

    Set SHA for QZ

    Remember to tell QZ to use the new sha.js package with this:

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

    Set Native Promises for QZ

    Remember to tell QZ to use the new sha.js package with this:

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