Here is the Full Code.
App.module.ts
import { NgModule, ErrorHandler } 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 { AppRoutingModule } from â./app-routing.moduleâ;
import { AppComponent } from â./app.componentâ;
import {NFC, Ndef} from â@ionic-native/nfc/ngxâ;
@NgModule({
declarations: [AppComponent],
entryComponents: ,
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
providers: [
NFC,
Ndef,
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
Mainpage.ts
import { Component } from â@angular/coreâ;
import { NFC, Ndef } from â@ionic-native/nfc/ngxâ;
import { NavController, Platform, AlertController, ToastController } from â@ionic/angularâ;
import { ChangeDetectorRef } from â@angular/coreâ;
@Component({
selector: âapp-tabsâ,
templateUrl: âtabs.page.htmlâ,
styleUrls: [âtabs.page.scssâ]
})
export class TabsPage {
tagid: any;
tagdesc: any;
constructor(public platform: Platform,
private alertCtrl: AlertController,
private toastCtrl: ToastController,
public navCtrl: NavController,
private nfc: NFC,
private ndef: Ndef,
private cdr: ChangeDetectorRef) {
this.platform.ready().then(() => {
this.addListenNFC();
});
}
addListenNFC() {
console.log(âenter into a addListenNFCâ);
this.tagid = ââ;
this.tagdesc = ââ;
this.nfc.addNdefListener(() => {
console.log('successfully attached ndef listener');
}, async (err) => {
console.log('error attaching ndef listener', err);
let toast = this.toastCtrl.create({
message: err,
duration: 1000,
position: 'bottom'
});
return (await toast).present();
}).subscribe(async (event) => {
console.log('received ndef message. the tag contains: ', event.tag);
console.log('decoded tag id', this.nfc.bytesToHexString(event.tag.id));
this.tagid = "";
this.tagdesc = "";
let tagId = await this.nfc.bytesToHexString(event.tag.id);
this.tagid = tagId;
if (event.tag.ndefMessage) {
let payload = event.tag.ndefMessage[0].payload;
let tagContent = await this.nfc.bytesToString(payload).substring(3);
this.tagdesc = tagContent;
}
let toast = this.toastCtrl.create({
message: this.nfc.bytesToHexString(event.tag.id),
//message: this.nfc.bytesToHexString(event.tag.ndefMessage[0].payload) && " --- " && this.nfc.bytesToHexString(event.tag.id) ,
duration: 5000,
position: 'bottom'
});
(await toast).present();
this.cdr.detectChanges();
});
}
}