0

I am trying to call an API after payment success. So I was calling Function inside razorPaySuccessHandler function but it is throwing error as below:

constructor(
  private userService: UserService
) { }

  paymentProcess() {
    let creditDialogRef = this.dialog.open(CreditFormComponent);
    creditDialogRef.afterClosed().subscribe(result => {
      this.userService.createOrder(this.id).subscribe(res => {

        // this.RAZORPAY_OPTIONS.amount = result.data.amount;
        this.RAZORPAY_OPTIONS.amount = '100';
        this.RAZORPAY_OPTIONS.order_id = '';

        // binding this object to both success and dismiss handler
        this.RAZORPAY_OPTIONS["handler"] = this.razorPaySuccessHandler.bind(this);

        let razorpay = new Razorpay(this.RAZORPAY_OPTIONS);
        razorpay.open();
      });
    });
  }

public razorPaySuccessHandler(response) {
        console.log("razorpay",response)
        if (response.razorpay_payment_id) {
          console.log(response, "Order Placed");
          this.razorpayResponse = `Razorpay Response`;
          this.userService.verifyOrder(this.orderId).subscribe(res=>{
              console.log(res)
          })
        }
        else {
          console.log("Payment failed")
        }
      }

I am getting error:

Uncaught TypeError: Cannot read property 'verifyOrder' of undefined
    at Ui.push../src/app/views/marketing/home-page/home-page.component.ts.HomePageComponent.razorPaySuccessHandler (home-page.component.ts:214)
    at checkout.js:1
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)

How do I call my own function or service inside it?

Anurag
  • 297
  • 2
  • 14
  • You most probably are having nested subscriptions. Also the code posted doesn't have reference to the `openSnackBar` shown in the error. Please post where the `razorPaySuccessHandler()` is called and where the `openSnackBar` is referenced. – ruth Jun 16 '21 at 13:47
  • @Michael D, check now, I have updated the Code – Anurag Jun 16 '21 at 13:52
  • Again, you haven't shown how the `razorPaySuccessHandler()` is triggered. Is it a callback? – ruth Jun 16 '21 at 13:57
  • It is called after payment success from Razorpay, in paymentProcess() function – Anurag Jun 16 '21 at 14:00
  • It's a callback. To refer the `this` to the outer scope you need to use JS [`bind`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind). Try: `this.RAZORPAY_OPTIONS["handler"] = this.razorPaySuccessHandler.bind(this);`. See the attached post for more info. – ruth Jun 16 '21 at 14:03
  • Additionally you have multiple nested subscriptions. They might lead to memory leak issues. You need to use a higher order mapping operator like `switchMap`. See here for more info: https://stackoverflow.com/a/63685990/6513921 – ruth Jun 16 '21 at 14:05

0 Answers0