import { Component , NgZone , OnInit } from '@angular/core' ; import { QRScanner , QRScannerStatus } from '@ionic-native/qr-scanner/ngx' ; import { NavController } from '@ionic/angular' ; import { AdddeviceService } from '../adddevice.service' ; import { UserService } from 'src/app/core/services/user.service' ; import { NoticeService } from 'src/app/core/services/notice.service' ; import { Router } from '@angular/router' ; @ Component ( { selector : 'qrscanner' , templateUrl : './qrscanner.page.html' , styleUrls : [ './qrscanner.page.scss' ] , providers : [ QRScanner ] } ) export class QrscannerPage { isShow = false ; constructor ( private qrScanner , private navCtrl , private adddeviceService , private userService , private noticeService , private router , private ngzone ) { } ngOnDestroy ( ) { this . exitScannerMode ( ) ; this . qrScanner . destroy ( ) ; } ionViewDidEnter ( ) { setTimeout ( ( ) => { this . scan ( ) ; this . entryScannerMode ( ) ; this . isShow = true ; } , 1000 ) ; } entryScannerMode ( ) { document . querySelector ( 'ion-app' ) . classList . add ( 'scannerMode' ) ; document . querySelector ( 'body' ) . classList . add ( 'scanner' ) ; } exitScannerMode ( ) { document . querySelector ( 'ion-app' ) . classList . remove ( 'scannerMode' ) ; document . querySelector ( 'body' ) . classList . remove ( 'scanner' ) ; } scan ( ) { this . qrScanner . prepare ( ) . then ( ( status ) => { if ( status . authorized ) { this . qrScanner . show ( ) ; this . startScan ( ) ; } else if ( status . denied ) { } else { } } ) . catch ( ( e ) => console . log ( 'Error is' , e ) ) ; } timeout = 0 ; startScan ( ) { setTimeout ( ( ) => { this . timeout = 5000 ; let scanSub = this . qrScanner . scan ( ) . subscribe ( ( text ) => { this . ngzone . run ( ( ) => { scanSub . unsubscribe ( ) ; console . log ( text ) ; let device ; try { device = JSON . parse ( text ) ; } catch ( error ) { } if ( typeof device != 'undefined' && typeof device . deviceType != 'undefined' ) { this . gotoGuide ( device ) ; } else if ( text . indexOf ( 'IMEI:' ) > - 1 ) { let imei = text . match ( /IMEI:(\S*);/ ) [ 1 ] ; this . adddeviceService . addDeviceByScan ( imei ) . then ( result => { if ( result ) { this . exitScannerMode ( ) ; this . qrScanner . hide ( ) ; this . gotoHome ( ) ; } else { this . startScan ( ) ; } } ) ; } else { this . noticeService . showToast ( '无效的二维码' ) ; this . startScan ( ) ; } } ) ; } ) ; } , this . timeout ) ; } gotoHome ( ) { this . navCtrl . navigateRoot ( '/' ) ; this . userService . getAllInfo ( ) ; } gotoGuide ( device ) { this . adddeviceService . isDev = device . isDev ; this . router . navigate ( [ '/adddevice' , device . deviceType ] ) ; } }