Search code examples
node.jsangularionic2nfc

how to call class without declaring it in constructor angular 2


I am trying to use NFC module of Ionic 2. This is my code:

nfc-scan.ts:

    import {Component} from '@angular/core';
    import {IonicPage, NavController, NavParams, Platform} from 'ionic-angular';
    import { Device } from '@ionic-native/device';
    import {NFC, Ndef} from '@ionic-native/nfc';

    @IonicPage()
    @Component({
        selector: 'nfc-scan',
        templateUrl: 'nfc-scan.html',
    })
    export class NfcScan {
        @ViewChild(Nav) nav: Nav;
NFC: NFC;

    constructor(public platform: Platform,
                    public navCtrl: NavController,
                    public navParams: NavParams,
        ) {

        }

    // NFC Scanning
        checkNFC()
        {
            this.NFC.enabled()
                .then(() => {
                    this.addListenNFC();
                })
                .catch(err => {
                    console.log(err);
                });
        }
    }

nfs-scan.html

<ion-content padding>
    <button on (click)="checkNFC()">Scan NFC</button>
</ion-content>

When I run the application, I get the error:

Property 'enabled' does not exist on type 'typeof NFC'.

I know I am not declaring NFC in the constructor of nfc-scan.ts. But when I do so, the page won't even load altogether.


Solution

  • I did finally manage to find a solution to this problem. It turns out that it's true you can't use a class without declaring it in the constructor of the class where you want to use it.

    In my case, the issue was, that I was running the app in my machine's (Macbook) browser, whereas NFC plugin can only be instantiated on a phone that supports NFC (Like camera plugin). Having said that, Ionic now provides ability to mock plugins in a way so that you can use them in your machine's browser.

    To use an Ionic Native plugin in the browser and ionic serve session, you just need to extend the original plugin class and override the methods you’d like to mock.

    Source: https://ionicframework.com/docs/native/browser.html

    Hope it helps someone like me.