Search code examples
javascriptangularcordovaionic-frameworkbarcode-scanner

Ionic barcode scanner timestamp integration


I just started to build my first ionic app with a barcode scanner on android. For the development of the barcode integration I used this documentation: https://www.djamware.com/post/59bb219f80aca768e4d2b13e/example-of-ionic-3-angular-4-cordova-barcode-and-qr-code-scanner

Everything works fine so far. But now I want to implement a timestamp to the output on the home.page.html after a barcode or qr-code got scanned.

Does anyone has an idea how to implement the timestamp?

Thank you so much in advance!

home.page.html:

<ion-header>
  <ion-toolbar color="primary">
    <ion-title>
      QR-Scanner
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>

  <ion-button color="success" expand="full" shape="round" (click)="scan()">Start Scan</ion-button>

    <ion-card *ngIf="productFound">
      <ion-card-header>
        <h2 color="success" >Object: {{selectedProduct.name}}</h2>
      </ion-card-header>
      <ion-card-content>
        <ul>
          <li>{{selectedProduct.plu}}</li>
          <li>{{selectedProduct.price}}</li>
          <li>{{selectedProduct.desc}}</li>
        </ul>
      </ion-card-content>
    </ion-card>
</ion-content>

home.page.ts:

import { NavController } from '@ionic/angular';
import { Component } from '@angular/core';
import { BarcodeScanner } from '@ionic-native/barcode-scanner/ngx';
import { Toast } from '@ionic-native/toast/ngx';
import { DataServiceService } from '../../app/data-service.service';


@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

    products: any[] = [];
    selectedProduct: any;
    productFound:boolean = false;
    public dateTime : string = '';

    constructor(public navCtrl: NavController,
      private barcodeScanner: BarcodeScanner,
      private toast: Toast,
      public dataService: DataServiceService) {

      this.dataService.getProducts()
      .subscribe((response)=> {
          this.products = <any[]>response
          console.log(this.products);
      });

      }

         scan() {
      this.selectedProduct = {};
      this.barcodeScanner.scan().then((barcodeData) => {
        this.selectedProduct = this.products.find(product => product.plu === barcodeData.text);
        if(this.selectedProduct !== undefined) {
          this.productFound = true;
        } else {
          this.productFound = false;
          this.toast.show(`Product not found`, '5000', 'center').subscribe(
            toast => {
              console.log(toast);
            }
          );
        }
      }, (err) => {
        this.toast.show(err, '5000', 'center').subscribe(
          toast => {
            console.log(toast);
          }
        );
      });
    }
}

data-service.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, Subject } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable({
  providedIn: 'root'
})
export class DataServiceService {

  constructor(private http: HttpClient) {  
    console.log('Hello DataServiceService Provider');

  }

      getProducts(){
        return this.http.get('assets/data/products.json')
        .map((res:Response)=>res.json());
    }
}

app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

import { BarcodeScanner } from '@ionic-native/barcode-scanner/ngx';
import { Toast } from '@ionic-native/toast/ngx';

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, 
    IonicModule.forRoot(), 
    AppRoutingModule,
    HttpClientModule
    ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    BarcodeScanner,
    Toast
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Solution

  • We can use Date which is provided by JS. So when you have made a scan, get that current timestamp and store it to your selectedProduct, for example in a property called scannedAt

    this.barcodeScanner.scan().then((barcodeData) => {
      this.selectedProduct = this.products.find(product => product.plu === barcodeData.text);
      if(this.selectedProduct !== undefined) {
        this.selectedProduct.scannedAt = new Date(); // add this!
        this.productFound = true;
      }
    // ...
    

    Then you can use the Angular DatePipe to decide how you want to show it in your template, for example with:

    {{ selectedProduct.scannedAt | date: 'short' }}