如何在读取第二个值之前禁用NFC EventListener



此问题来自NFC标签过于敏感。当我放置一次NFC标签时,会瞬间输入太多值。因此,如果输入了一个NFC标签值,则希望在该时刻停止NFC事件侦听器。我该如何实现它?

我认为设备和NFC标签之间的NFC读取速度比程序端的EventListener取消速度快。

这个离子页面是这样工作的

*1( 第一次加载ViewDidEnter((

2( 添加addListeNFC((

3( 如果已标记NFC,则将值发送到onNfcLogin(tagId(

4( 在onNfcLogin(tagId(中,这包括作为userService.nfclogin((的"Http post-service provider">

5( 最后从服务器端得到json类型的返回。*

{"依赖项":{"离子天然/核心":"4.7.0","离子角":"3.9.2","typescript":"~2.6.2"]},"测试装置":"Galaxy8","NFC标签":"便宜的NFC棒"}

ionViewDidEnter() {
this.nfc.enabled().then((resolve) => {
this.addListenNFC();
}).catch((reject) => {
alert("NFC is not supported by your Device");
});
}

addListenNFC() {
this.nfc.addTagDiscoveredListener().subscribe(data => {
//window.removeEventListener; //this is not working.
if (data && data.tag && data.tag.id) {
this.tagId = this.nfc.bytesToHexString(data.tag.id);
if (this.tagId) {
this.scanned = true;
this.onNfcLogin(this.tagId);
} else {
alert('NFC_NOT_DETECTED');
}
}
});
}

onNfcLogin(tagId) {
this.userService.nfclogin(tagId).subscribe(data => { 
// "this.userService.nfclogin()" is at Http post service provider
this.getData = JSON.stringify(data);
if (this.getData) {
this.granted = true;
this.loading.dismiss();
this.events.publish('user:login');
this.navCtrl.setRoot(HomePage);
}
this.resetScanData;
},
error => {
this.loading.dismiss();
this.showError(error);
});
}

showError(error) {
console.log(error);
let alert = this.alertCtrl.create({
title: 'Login Error',
message: error.json().message,
buttons: ['OK']
});
alert.present();
}

resetScanData() {
this.granted = false;
this.scanned = false;
this.tagId = "";
}

您只能使用observatory.take(1(.subscribe(…(进行第一次订阅。
然后重新创建订阅。

我用这段代码解决了问题。

this.myListener = this.nfc.addNdefListener(() => {
console.log(‘successfully attached ndef listener’);
},(err) => {
console.log(‘error attaching ndef listener’, err);
}).subscribe((event) => {
. . .
});
//remove listener
this.myListener.unsubscribe();

感谢爱奥尼亚论坛的Avdm。https://forum.ionicframework.com/t/remove-listener-nfc-plugin/113393

最新更新