1

I'm trying to write an if statement after a completed purchase. I'm using this tutorial.

purchase() {
  if (!this.platform.is('cordova')) { return };

  let productId;

  if (this.platform.is('ios')) {
    productId = this.product.appleProductID;
  } else if (this.platform.is('android')) {
    productId = this.product.googleProductID;
  }

  console.log('Products: ' + JSON.stringify(this.store.products));
  console.log('Ordering From Store: ' + productId);
  try {
    let product = this.store.get(productId);
    console.log('Product Info: ' + JSON.stringify(product));
    let order = await this.store.order(productId);
    alert('Finished Purchase');
  } catch (err) {
    console.log('Error Ordering ' + JSON.stringify(err));
  }
}

I'm trying to load a new screen with data (content and gameGear), once the user completes the purchase:

goToReference() {
  this.purchase();
  if(this.purchase() === 'Finished Purchase'){
    this.navCtrl.push(ReferencePage,{
      content: this.content,
      gameGear: this.gameGear
    });
  } else {
    return
  }
}

However the error I keep getting is:

Operator '===' cannot be applied to types 'Promise' and 'string'.

Not sure how to get around this issue or if there's easier syntax to fire off the this.purchase() once the purchase has been completed.

David Walschots
  • 12,279
  • 5
  • 36
  • 59
cdh429
  • 337
  • 3
  • 11
  • 20

1 Answers1

1

As a starting remark let me say that your code executes a purchase twice, due to purchase being called two times.

this.purchase();
if(this.purchase() === 'Finished Purchase')

The error indicates that you are comparing the returned value of the purchase function with the 'Finished Purchase' string. There are two things to note in your current code that cause this:

  1. The purchase function is asynchronous (even though it seems you removed the async keyword from your code sample). The async function returns a Promise. You can see the accepted answer here to understand more about asynchronicity and promises.

  2. You're not returning the 'Finished Purchase' string, but are showing a browser alert popup. Therefore in fact the returned value of purchase is void, combined with promises the exact type becomes Promise<void>.

I'm going to assume you want purchase to return whether or not the purchase succeeded. For the example I remove all cluttering code:

async purchase() {
  try {
    let order = await this.store.order(productId);
    return true;
  } catch (err) {
    return false;
  }
}

async goToReference() {
  if(await this.purchase()) {
    this.navCtrl.push(ReferencePage,{
      content: this.content,
      gameGear: this.gameGear
    });
  }
}

Above, the return type of purchase is Promise<boolean>.

David Walschots
  • 12,279
  • 5
  • 36
  • 59