我使用角度与firebase实时数据库。我有一个应用程序为订单进行付款处理。当前代码如下所示
我的离子页面.ts在paynow按钮上调用,如下所示:
startPayment(){
this.instamojoClient = new Instamojo(this.http, this.iab, 'XXX');
var data = this.instamojoClient.getPaymentFields()
this.instamojoClient.payNow(data).then(response => {
//payment is successful now create a order for the customer
this.ddlSvc.createOrder(this.core.order, this.core.user)
}).catch(err => {
console.log("Payment failed: " + JSON.stringify(err))
});
}
createOrder如下所示
createOrder(order:Order, customer:User){
console.log("new technique to creating new order for #" + order.orderNumber)
const itemRef = this.db.list('orders')
const payload = {
order: order,
customer: customer
}
itemRef.push(payload).then(
(data) => {
const orderKey = data.key
//create a cross entry in the user as well to maintain history
const userRef = this.db.object('/users/' + customer.uid + "/orders/" + orderKey )
userRef.set(order)
}
)
}
我有几个问题/问题:1。startPayment应该能够等到createOrder完成,以便我可以向用户显示一条消息,以便成功处理订单。我从createOrder服务函数返回什么来实现呢?
简单地回复承诺。在伪代码中:
startPayment().then()
startPayment(): Promise {
//...
return payNow.then(() => {
return createOrder();
});
}
createOrder(): Promise {
// ...
return itemRef.push...
}
但是,通过使用反应模式,您可以使您的生活更轻松:
startPayment.subscribe(() => {
// success
}, error => {
// error
})
startPayment(): Observable<any> {
return from(payNow()).pipe(
switchMap(dataFromPayNow => createOrder(dataFromPayNow))
);
}
createOrder(): Observable<any> {
//...
return from(itemRef.push()).pipe(
switchMap(item => {
return from(userRef.set());
})
)
}
您可以使用catchError运算符来处理流中的错误。