Barcode Scanner results from API

Hi im trying to return a result from a barcode scan result. i have an read api that is returning a JSON of products by barcode,

this Is the API

getProduct(qrBarcode: string): Observable<Product[]> {
    return this.http.get(`${this.ApiUrl}/product/read_product.php?barcode=${qrBarcode}`)
    .map(res => <Product[]>res.json());
  }

i am then calling the API in my barcode Scanner Page like so:

this.apiProvider.getProduct(this.qrBarcode).subscribe(products => {
    this.products = products;
  })

i want to scan the barcode and use the barcode number returned to filter the API, here is my full function:

export class HomePage {
scannedCode = null;
qrBarcode: string;
results: string;
products: Product;

constructor(public navCtrl: NavController, public navParams: NavParams, private barcodeScanner: BarcodeScanner, public apiProvider: ApiProvider ) {

}
scanCode(){
this.barcodeScanner.scan().then(barcodeData => {
this.scannedCode = barcodeData.text;
}, (err) =>{
console.log(‘Error’, err);
});
this.qrBarcode = this.scannedCode;

this.apiProvider.getProduct(this.qrBarcode).subscribe(products => {
this.products = products;
})

}

ionViewWillEnter(){
this.scanCode();
}
}

i am currently getting the barcode to return the data but the API isn’t returning its result. any help on this would be brilliant.

The barcodeScanner is returning a promise (barcodeData) which you set to your scannedCode variable.

However, you are directly making the API call after you call the scanner, so the promise is not yet received at that point! Basically, qrBarcode will be null at the point where you currently use it.

Try to move your getProduct() into the completion block of the scan() function and then the API call should be triggered with the right value.

hi saiman, thankyou so much we discovered two issues, firstly your input resolved the first issue, second issue i had my model compiled inccorectly once reorderd it worked a treat. many thanks

hi Saimon, this worked for me, but now i cannot get access to a specific field inside of the data, see snipped from below, it returns NaN.

scanCode(){
this.barcodeScanner.scan().then(barcodeData => {

this.scannedCode = barcodeData.text;
this.qrBarcode = this.scannedCode;

this.apiProvider.getProduct(this.qrBarcode).subscribe(products => {
  this.products = products;
  this.dosingRequirement = products[1].Dosage;
  
})
//test api calculations
//this.dosage = this.products[6];
this.totalVolume = this.tankVolume;
this.dosage = this.dosingRequirement * this.totalVolume;
//return this.dosage;

}, (err) =>{
console.log(‘Error’, err);
alert(‘Sorry this product is not in our Database’);
});
}