NFC ionic V2 -- not work

Hi, please help me, This code does not work for me?

import { Component, NgZone } from '@angular/core';
import { NavController, AlertController, Platform } from 'ionic-angular';
import { NFC, Ndef } from 'ionic-native';

@Component({
  selector: 'page-scan',
  templateUrl: 'scan.html'
})
export class ScanPage {

  public tag:any;

  constructor(public navCtrl: NavController, private Alert: AlertController, private zone: NgZone,private platform: Platform) {
    this.tag = {};
  }

  ionViewWillEnter(){
    this.platform.ready().then(() => {
      this.cekNFC();
    });
  }

  cekNFC() {
    NFC.enabled()
      .then(() => {
        console.log("NFC is ready");
        this.addListenNFC();
        // IF Disabled
      })
      .catch(err => {
        console.log(err);
        let alert = this.Alert.create({
          subTitle : "NFC DISABLED",
          buttons: [{ text : "OK"},{ text : "Go Setting",
            handler : () => {
              NFC.showSettings();
            }
          }]
        });
        alert.present();
      });
  }

  addListenNFC() {
    console.log("Listening...");
    NFC.addNdefListener(nfcEvent => this.sesReadNFC(nfcEvent.tag)); // <-- does not work for me
  }

  sesReadNFC(data):void {
    this.tag = JSON.parse(JSON.stringify(data, null, 4));
    console.log(JSON.stringify(data, null, 4));
  }

}
1 Like

Hi

I see that addNdefListener returns a Promise

you can change your code to:

NFC.addNdefListener().subscribe(nfcData => {
   console.log("Receved NFC tag: " + JSON.stringify(nfcData));
}

This method works for me,

1 Like

Thank you for the response, your snippet work (although you are missing the closing parenthesis and semicolon).
Is it possible to use the then() method instead the observable subscribe?
In the Ionic Native docs it stands:

Ionic Native wraps plugin callbacks in a Promise or an Observable

But if I write:

NFC.addNdefListener().then(nfcData => {
   alert("Receved NFC tag: " + JSON.stringify(nfcData));
});

I get the ā€œProperty ā€˜thenā€™ does not exist in type ā€˜Observableā€™ā€
Tried also with toPromise() but no luck.

ā€œno luckā€ isnā€™t very descriptive. toPromise should work, but is there a specific reason you donā€™t just want to use the Observable?

I get the same TypeScript error:

Property ā€˜toPromiseā€™ does not exist on type ā€˜Observableā€™

The only reason why I avoid Observables is that I am not yet familiar with them. So donā€™t know how to catch the exceptions for example. I read that they are a lot more flexible than promises but still I need to understand them before using. And I am confused because in the docs about NFC it stands that addNdefListener returns Promise :confused:

You will probably have to import it explicitly:

import "rxjs/add/operator/toPromise";

I still think investing the time to get familiar with Observables will benefit you.

1 Like