1. 程式人生 > >Ionic3 生成專案及掃描二維碼

Ionic3 生成專案及掃描二維碼

建立專案

ionic start devdacticQRCodes blank
cd devdacticQRCodes
// 安裝外掛
npm install ngx-qrcode2 --save
ionic cordova plugin add phonegap-plugin-barcodescanner
npm install --save @ionic-native/barcode-scanner

修改App.Module.ts

src/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser'
; import { ErrorHandler, NgModule } from '@angular/core'; import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular'; import { SplashScreen } from '@ionic-native/splash-screen'; import { StatusBar } from '@ionic-native/status-bar'; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'
; // 引入外掛 import { NgxQRCodeModule } from 'ngx-qrcode2'; import { BarcodeScanner } from '@ionic-native/barcode-scanner'; @NgModule({ declarations: [ MyApp, HomePage ], imports: [ BrowserModule, IonicModule.forRoot(MyApp), NgxQRCodeModule ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage ], providers: [ StatusBar, SplashScreen, {provide: ErrorHandler, useClass: IonicErrorHandler}, BarcodeScanner ] }) export class
AppModule {
}

修改 app/pages/home/home.html

<ion-header>
  <ion-navbar>
    <ion-title>
      QR Code App
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-item>
    <ion-input type="text" placeholder="MY QR Code data" [(ngModel)]="qrData">
    </ion-input>
  </ion-item>
  <!--新增按鈕-->
  <button ion-button full icon-left (click)="createCode()"><ion-icon name="barcode"></ion-icon>Create Code</button>
  <button ion-button full icon-left (click)="scanCode()" color="secondary"><ion-icon name="qr-scanner"></ion-icon>Scan Code</button>

  <ion-card *ngIf="createdCode">
    <ngx-qrcode [qrc-value]="createdCode"></ngx-qrcode>
    <ion-card-content>
      <p>Value: {{ createdCode }}</p>
    </ion-card-content>
  </ion-card>

  <ion-card *ngIf="scannedCode">
    <ion-card-content>
      Result from Scan: {{ scannedCode }}
    </ion-card-content>
  </ion-card>
</ion-content>

home.ts

import { Component } from '@angular/core';
import { BarcodeScanner } from '@ionic-native/barcode-scanner';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  qrData = null;
  createdCode = null;
  scannedCode = null;

  constructor(private barcodeScanner: BarcodeScanner) { }

  createCode() {
    this.createdCode = this.qrData;
  }

  scanCode() {
    this.barcodeScanner.scan().then(barcodeData => {
      this.scannedCode = barcodeData.text;
    }, (err) => {
        console.log('Error: ', err);
    });
  }

}

測試

同時在瀏覽器和手機執行,在瀏覽器生成二維碼,再用手機掃描該二維碼。

生成二維碼

這裡寫圖片描述