nativescript-nfc
nativescript-nfc copied to clipboard
How to write service?
I can't get routerExtension inside callback when i write service
component:
` @Component({ selector: 'app-sporttrack', templateUrl: './sporttrackSearch.component.html', styleUrls: ['./sporttrack.component.scss'] }) export class SporttrackSearchComponent implements OnInit, OnDestroy { constructor(public routerExtensions: RouterExtensions, private nfc: SporttrackNfcService, public zone: NgZone) { }
ngOnInit(): void {
this.nfc.doStartTagListener.bind(this)
this.nfc.doStartTagListener(this.searchAthlet).then(() => console.log(this))
}
ngOnDestroy(): void {
this.nfc.doStopTagListener()
}
searchAthlet(data: NfcTagData) {
this.routerExtensions.navigate(['sporttrack', athlet.phone])
}
}
` service
` @Injectable({ providedIn: 'root' }) export class SporttrackNfcService { nfc: Nfc
constructor() {
this.nfc = new Nfc()
}
doStartTagListener(fn: (data: NfcTagData) => any): Promise<any> {
return this.nfc.setOnTagDiscoveredListener((data: NfcTagData) => {
console.dir(data, this.nfc)
console.log('Tag discovered sporttrack scan! ' + JSON.stringify(data))
fn(data)
}).then(() => {
console.log('OnTagDiscovered Listener set')
}, (err) => {
console.log(err)
})
}
doStopTagListener() {
this.nfc.setOnTagDiscoveredListener(null).then(() => {
console.log('OnTagDiscovered nulled')
}, (err) => {
console.log(err)
})
}
}
`
ERROR `
Tag discovered sporttrack scan! {"id":[4,72,-37,26,-32,95,-127],"techList":["android.nfc.tech.NfcA","android.nfc.tech.MifareUltralight","android.nfc.tech.NdefFormatable"]}
JS: 123
JS: Unhandled Promise rejection: Cannot read property 'routerExtensions' of undefined ; Zone:
`
ngOnInit(): void { this.zone.runOutsideAngular(() => { this.nfc.doStartTagListener(this.searchAthlet.bind(this)) }) }
doStartTagListener(fn: (data: NfcTagData) => any): Promise<any> { return this.nfc.setOnTagDiscoveredListener((data: NfcTagData) => { console.dir(data, this.nfc) console.log('Tag discovered sporttrack scan! ' + JSON.stringify(data)) this.zone.run(() => fn(data)) }).then(() => { console.log('OnTagDiscovered Listener set') }, (err) => { console.log(err) }) }
I resolve this