我正试着在完成购买后写一份if声明。我正在使用这教程。
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));
}
}一旦用户完成购买,我将尝试加载一个包含数据(内容和gameGear)的新屏幕:
goToReference() {
this.purchase();
if(this.purchase() === 'Finished Purchase'){
this.navCtrl.push(ReferencePage,{
content: this.content,
gameGear: this.gameGear
});
} else {
return
}
}然而,我一直遇到的错误是:
运算符'===‘不能应用于类型’答应‘和’字符串‘。
不知道如何绕过这个问题,或者一旦购买完成,是否有更容易的语法触发this.purchase()。
发布于 2018-03-30 23:01:39
首先,请允许我说,您的代码执行了两次购买,因为purchase被调用了两次。
this.purchase();
if(this.purchase() === 'Finished Purchase')此错误指示您正在将purchase函数的返回值与'Finished Purchase'字符串进行比较。在当前代码中有两件事需要注意,这是导致以下情况的原因:
purchase函数是异步的(尽管您似乎从代码示例中删除了异步关键字)。异步函数返回一个Promise。您可以看到接受的答案这里,以了解更多关于异步性和承诺的知识。'Finished Purchase'字符串,而是显示一个浏览器警报弹出。因此,实际上,purchase的返回值是void,再加上确切的类型将成为Promise<void>。我将假设您希望purchase返回,无论购买成功与否。例如,我删除了所有杂乱无章的代码:
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
});
}
}上面,purchase的返回类型是Promise<boolean>。
https://stackoverflow.com/questions/49539374
复制相似问题