Hi, I have two different scenarios receiving data from service and one way data will not be rendered before I click on button or open menu. I don’t understand the difference, can somebody please explain.
This is my service where I hold and change two example values and also push event to detect change in page component.
import {Injectable} from 'angular2/core';
import {Events} from 'ionic-angular';
import {Http} from 'angular2/http';
@Injectable()
export class NFCService {
static get parameters() {
return [[Http], [Events]];
}
constructor(http, events) {
this.http = http;
this.events = events;
this._nfcData = {};
this.random = {}
}
parseNfcData(nfcEvent) {
let tag = nfcEvent.tag;
let ndefMessage = tag.ndefMessage;
let parsedNfcData = nfc.bytesToString(ndefMessage[0].payload);
this._nfcData = parsedNfcData;
this.events.publish('nfc:gotNfcData');
}
renderRandom() {
this.random = "renderRandom";
this.events.publish('random:gotRandomData');
}
}
This is my Page where I use event listeners for value changes. I also call this.renderRandomData() function in this component to show that this way data will be rendered if it got event back from service (random:gotRandomData). But if I read NFC tag and call service with the data from app.js I do receive data in console log on nfc:gotNfcData, but it renders after clicking on some button.
import {Page, NavController, NavParams, Events} from 'ionic-angular';
import {NFCService} from '../../providers/nfc-service';
@Page({
templateUrl: 'build/pages/hello-ionic/hello-ionic.html'
})
export class HelloIonicPage {
static get parameters() {
return [[NavController], [NavParams], [Events], [NFCService]];
}
constructor(nav, navParams, events, nfcService) {
this.nav = nav;
this.events = events;
this.nfcService = nfcService;
this.data = {};
this.random = {};
this.listenToNFCEvents();
setTimeout(() => {
this.renderRandomData();
}, 2000);
}
listenToNFCEvents() {
this.events.subscribe('nfc:gotNfcData', () => {
console.log("Got nfc data");
this.data = this.nfcService._nfcData;
console.log(this.data);
});
this.events.subscribe('random:gotRandomData', () => {
console.log("Got random data");
this.random = this.nfcService.random;
});
}
renderRandomData() {
this.nfcService.renderRandom();
}
}
That’s how I detect nfc tag in app.js after platform ready and pass data for rendering to the same service
nfc.addMimeTypeListener("text/any", (res) => {
// console.log(res);
return this.nfcService.parseNfcData(res);
}, success, failure);
And this is HTML where I show them.
<h3>{{data}}</h3>
<h3>{{ random }}</h3>