androidangularionic-frameworknfc

Ionic Angular NFC Changedetection Problem


I have a problem using an actual Ionic Angular in combination with NFC reader.

I can successfully read the NFC Tag with the example provided in:

https://ionicframework.com/docs/native/nfc

The Problem that i have is, that after the reading of the NFC somehow the Angular ChangeDetection is broken and the changes are not displayed. When i click on a button that does nothing, the changes are displayed.

I know i can trigger the ChangeDetection manually, which would work, but then i would have to trigger the ChangeDetection everywhere in the component, which i think should not be the case.

Does anyone have an idea what i am doing wrong?

First i thought maybe it has something to do with the observable, but i tried adding a interval observable, which works just like expected.

Template:

<p><ion-button (click)="startNFC()">start NFC readermode</ion-button></p>
<p><ion-button (click)="startNFCListener()">start NFC listener</ion-button></p>
<p><ion-button (click)="startInterval()">start Interval</ion-button></p>
<p><ion-button (click)="doNothing()">do nothing</ion-button></p>
<p>
  {{nfcReading}}
  {{nfcTag}}
  <ion-spinner *ngIf="nfcReading"> </ion-spinner>
</p>

Code:

startNFC() {
  console.log("startNFC");
  this.nfcReading = true;
  let flags = this.nfc.FLAG_READER_NFC_A | this.nfc.FLAG_READER_NFC_V;

  this.readerModeSub = this.nfc.readerMode(flags).subscribe(
  tag => {
    console.log(JSON.stringify(tag));
    this.nfcTag = this.nfc.bytesToHexString(tag.id);
    this.nfcReading = false;
    this.readerModeSub.unsubscribe();

  },
  err => {
    console.log("Error reading tag", err);
    this.nfcReading = false;
  }
);

}

doNothing() {
// this really does nothing... it is just to demonstrate that this triggers the changedetection
}

i get can see that the subsciption event is triggered in console, but it is not shown in the HTML. When clicking the do nothing Button. The tag is shown.

I created a fresh type=angular blank project and test on a Google Pixel 3a hardware.

i have uploaded a sample project to demonstrate my problem. https://github.com/autlunatic/Ionic-NFC-Android-Test/


Solution

  • I guess the answer would have been in the docs. You need to run the listener inside of ngZone.

    https://capacitorjs.com/docs/guides/angular#ngzone

     Network.addListener("networkStatusChange", (status) => {
        this.ngZone.run(() => {
          // This code will run in Angular's execution context
          this.networkStatus = status.connected ? "Online" : "Offline";
        });
      });
    

    credits also goes to:
    after close Interstitial ad then angular not able to detect changes on next page in capacitor/ionic