Ionic Cordova NFC 未订阅或捕获事件

问题描述 投票:0回答:1

如何解决 Ionic Cordova 应用程序在使用 NFC PhoneGap API 时未订阅 NDEF 侦听器的问题

功能:

startNFCReading() {
console.log('Starting NFC reading...');

        if (!this.nfc) {
            console.log('NFC library not found');
            return;
        }

        this.nfc
            .enabled()
            .then(() => {
                console.log('NFC enabled');
                const attachListener = this.nfc.addNdefListener(
                    (event: any) => {
                        console.log('Successfully attached ndef listener');
                    },
                    (err: any) => {
                        console.log('Error attaching ndef listener', err);
                    }
                ).subscribe((event) => {
                        console.log('received ndef message. the tag contains: ', event);
                        console.log('decoded tag id', this.nfc.bytesToHexString(event.tag.id));
                        this.getProduct(event.tag.ndefMessage);
                }
                );
            })
            .catch((e) => {
                console.log('NFC not enabled', e);
                // Handle NFC not enabled error here, e.g., show a user-friendly message.
            });
        console.log('After subscription');

    }

控制台输出

开始 NFC 读取...

7239.d181bf1e42e46154a791.js:1 订阅后

7239.d181bf1e42e46154a791.js:1 NFC已启用

7239.d181bf1e42e46154a791.js:1 已成功附加 ndef 侦听器

控制台输出表明它成功附加了 NDEF 侦听器,但没有转到订阅事件。我已经尝试调试它,但问题仍然存在。是什么原因导致这个问题,我该如何解决它?

javascript android cordova ionic-framework phonegap
1个回答
0
投票

查看文档,您似乎在

addNdefListener
调用中需要 3 个函数:

addNdefListener: function (callback, win, fail)

所以我认为你的第一个功能

(event: any) => {
  console.log('Successfully attached ndef listener');
}

当您希望将其用作

callback
时,正在用作
win

尝试删除

subscribe
调用并将该函数作为
callback
:

const attachListener = this.nfc.addNdefListener(
  (event) => {
    console.log('received ndef message. the tag contains: ', event);
    console.log('decoded tag id', this.nfc.bytesToHexString(event.tag.id));
    this.getProduct(event.tag.ndefMessage);
  },
  () => {
    console.log('Successfully attached ndef listener');
  },
  (err: any) => {
    console.log('Error attaching ndef listener', err);
  });
© www.soinside.com 2019 - 2024. All rights reserved.