HTTP call from inside ionic-native component


#1

I’m not sure what is wrong with my code, but I can’t seem to make it work.
Basically I’m trying to get the a text from the barcode reader plugin then make an http request from a service.

Code snippet:

openBarCodeScanner(){
  BarcodeScanner.scan().then(function(data) {
  console.log(data.text);
  if (data.cancelled == false) {
    console.log('inside if');

    this._bookService.findBookOnline(data.text).subscribe(
      bookOnline => {
        console.log('inside findBookOnline')
        this.bookOnline = bookOnline;
        console.log(bookOnline);
        this.nav.push(BookDetailComponent, { selectedBookOnline: bookOnline })
      },
      err => console.log(err),
      () => console.log('DONE')
      );
  }
 });
}

And in my bookService I’m returning the value like:

 findBookOnline(ISBN: String){
   //some code
   ...
   return this.http.get(url).map( res => <BookOnline>res.json().results[0]); 
 }

I am getting the value from the BarcodeScanner successfully, but can’t call the bookService !
I tried calling the bookService outside the BarcodeScanner plugin, and it worked perfectly.

Anyone faced this type of issue ?


#2

Hi

Use the arrow function to keep the context (this):

BarcodeScanner.scan().then((data) => {
...
this._bookService...
...
});

#3

Hi @nbamj,

Problem is of USING Context “this” inside BarcodeScanner.scan(), in which this refer to the BarcodeScanner Class instead of component.
you can store “this” context into another temporary variable, utilize it.

openBarCodeScanner(){
   let self = this;

   BarcodeScanner.scan().then(function(data) {

   console.log(data.text);

   if (data.cancelled == false) {
      console.log('inside if');

      self._bookService.findBookOnline(data.text).subscribe(
          bookOnline => {
          console.log('inside findBookOnline')
          self.bookOnline = bookOnline;
          console.log(bookOnline);
          self.nav.push(BookDetailComponent, { selectedBookOnline: bookOnline })
      },
      err => console.log(err),
          () => console.log('DONE')
      );
   }
  });
}

#4

store this on a temp variable is not the best way.
follow @infoproducts advice and use the fat arrow functionality.

Or if you want to bind this to the context use “.bind”

fat arrow:

BarcodeScanner.scan().then((data) => {
  ...
  this._bookService...
  ...
});

bind this:

BarcodeScanner.scan().then(function(data) {
  ...
  this._bookService...
  ...
}.bind(this));

#5

@infoproducts, @itsmemyk & @bengtler

You guys are awesome.
Got it working now with the arrow function.