0

我正在使用 Angular 6 应用程序,用户可以在其中购买产品。如果用户选择产品并按下立即付款按钮,则会调用以下 API。

doPay() {
        this.http.post('https://testpayment?action=payproduct', params, options).subscribe(
            data => {
                console.log("Cart payment done.", data);
                this.getProductList(); // API call
                this.getUserDetails(); // API call
                var callback = () => {
                    // Make sure getProductList and getUserDetails APIs got executed and response received
                    // Perform redirection here
                };
                Globals.alert("You have successfully purchased product","OK", callback);
            },
            error => {
                console.error("Cart payment error!", error);
            }
        );
    }

在这里,如果 payproduct 成功并且有警报回调,我将显示警报/弹出消息。

此回调决定付款后重定向页面的位置。在这个回调中,我想在收到 getProductList 和 getUserDetails 响应后执行一些代码。

谁能指导我如何确保收到 getProductList 和 getUserDetails 响应,以便我可以根据它进行页面重定向

getProductList()
{
   this.http.get('some_url).subscribe(
    data => {
       console.log("Product list:", data);
       this.my_products = data;  
       for (var i in this.my_products) {  
         this.getPurchasedItem(this.my_products[i].Id);  
       }  
     }  
    )  
}  
getPurchasedItem(id) {
        this.http.get('some_url').subscribe(
            data => {
                console.log("Item:", data);
                for (let i=0; i< this.my_products.length; i++) {
                    if (this.my_products[i].ItemCode == data['ItemCode']){
                        this.my_products[i] = data;
                    }
                }
            },
            error => {
                console.error("error!", error);
            }
        );
    }

谢谢

4

1 回答 1

0

假设this.getProductList();定义为:

getProductList()
{
  return this.http.post("some_url",params,options);
}

this.getUserDetails();定义为:

getUserDetails()
{
  return this.http.post("some_url",params,options);
}

那么您可以确保这些 API 调用是通过使用 subscribe 来执行的,例如:

doPay() {
        this.http.post('https://testpayment?action=payproduct', params, options).subscribe(
            data => {
                console.log("Cart payment done.", data);
                this.getProductList().subscribe(dat=>{
                   this.getUserDetails().subscribe(da=>{
                      var callback = () => {
                      // Perform redirection here
                      };
                      Globals.alert("You have successfully purchased product","OK", callback);
                   },er=>console.log(er));
                },err=>console.log(err));
            },
            error => {
                console.error("Cart payment error!", error);
            }
        );
    }

这样,重定向仅在执行两个 API 调用时才会发生。

于 2021-06-21T14:25:53.513 回答