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

}

测试

同时在浏览器和手机运行,在浏览器生成二维码,再用手机扫描该二维码。

生成二维码

这里写图片描述

内容来源:
https://ionicacademy.com/ionic-qr-code-generator-reader/

相关文章
相关标签/搜索