NFC ionic V2 -- not work


#1

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));
  }

}

#2

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,


#3

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.


#4

“no luck” isn’t very descriptive. toPromise should work, but is there a specific reason you don’t just want to use the Observable?


#5

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:


#6

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.