I’m stuck for weeks trying read NFC card from my ionic project.
Running the app on a real device (Samsung S7 Edge with Android).
I’m following this:
Then, I installed the plugin on my project:
ionic cordova plugin add phonegap-nfc
npm install @ionic-native/nfc
Only need read the Card Tag Id into the variable tagId (string) to show it.
My source:
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 { NFC, Ndef } from '@ionic-native/nfc/ngx';
@NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
NFC,
Ndef,
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
home.ts
import { Component } from '@angular/core';
import { NavController, Platform, AlertController, ToastController } from 'ionic-angular';
import { NFC, Ndef } from '@ionic-native/nfc/ngx';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
tagId: string;
constructor(public platform: Platform,
private alertCtrl: AlertController,
private toastCtrl: ToastController,
public navCtrl: NavController,
private nfc: NFC,
private ndef: Ndef) {
this.platform.ready().then(() => {
this.addListenNFC();
});
} // del constructor
addListenNFC() {
console.log('entra a addListenNFC');
this.nfc.addNdefListener(() => {
console.log('successfully attached ndef listener');
}, (err) => {
console.log('error attaching ndef listener', err);
let toast = this.toastCtrl.create({
message: err,
duration: 1000,
position: 'bottom'
});
toast.present();
}).subscribe((event) => {
console.log('received ndef message. the tag contains: ', event.tag);
console.log('decoded tag id', this.nfc.bytesToHexString(event.tag.id));
let toast = this.toastCtrl.create({
message: this.nfc.bytesToHexString(event.tag.id),
duration: 1000,
position: 'bottom'
});
toast.present();
});
}
}
home.html
<ion-content padding>
<h1>Please Scan Access Card</h1>
<ion-card>
<ion-card-content>
<p>Account Tag ID: {{ tagId }}</p>
</ion-card-content>
</ion-card>
</ion-content>
I’m getting the following error in the console:
Why do I get this error when adding the listener?
What is wrong??
Thanks.