我正在建立一个在线商店,我正在使用 paystack payment gateway ,在 api 中,我尝试在支付网关 api 内运行一个函数,但它不起作用。这是代码:
payWithPaystack(returnData, amount){
const binded = this.service.completePayment.bind(this)
var handler = PaystackPop.setup({
key: '.......',
email: this.details.email,
amount: amount,
currency: "NGN",
ref: `ref-${Math.ceil(Math.random() * 10e13)}`,
metadata: {
custom_fields: [{
display_name: this.details.firstName+' '+this.details.lastName,
variable_name: "mobile_number",
value: this.details.phoneNumber
}]
},
callback(res){
console.log(res)
binded(res);
},
onClose(){
console.log('window closed');
this.color='danger'
this.payDisplay='Transaction closed'
this.payClick=false
}
});
handler.openIframe();
}
在服务页面中,这是代码
completePayment(sentData){
console.log('enter')
this.http.post(`${this.ApiURL}payAm.php`, sentData, {headers:this.headers})
.subscribe(data=>console.log('ok'), error=>console.log(error))
}
现在的问题是函数completePayment
正在部分调用,console.log正在运行,但它没有发送http请求,请问我该如何解决这个问题
最佳答案
编写 payWithPaystack
方法,使其返回一个 promise :
payWithPaystack(amount){
return new Promise( (resolve,reject) => {
var handler = PaystackPop.setup({
key: '.......',
email: this.details.email,
amount: amount,
currency: "NGN",
ref: `ref-${Math.ceil(Math.random() * 10e13)}`,
metadata: {
custom_fields: [{
display_name: this.details.firstName+' '+this.details.lastName,
variable_name: "mobile_number",
value: this.details.phoneNumber
}]
},
callback(res){
console.log(res)
//RESOLVE promise
resolve(res);
},
onClose(){
console.log('window closed');
//REJECT promise
reject('window closed');
}
});
handler.openIframe();
});
}
然后使用它返回的 promise :
this.payWithPaystack(amount)
.then( sentData => {
console.log('enter', sentData);
this.http.post(`${this.ApiURL}payAm.php`, sentData, {headers:this.headers})
.subscribe(data=>console.log('ok'), error=>console.log(error))
}).catch( reason => {
console.log("rejected: ", reason);
this.color='danger'
this.payDisplay='Transaction closed'
this.payClick=false;
});
Promise 是链接异步操作的最佳方式。
关于javascript - 如何在 Angular 中调用另一个函数内的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58975067/