angularscopeclosurespayumoney

Could not call outside function from bolt Response Handler Callback


I could not able to call my Update method from the bolt responseHandler:, please help me on this issue.

Angular 9:

Error: core.js:1673 ERROR TypeError: this.updatePaymentInfo is not a function at Object.responseHandler

The updatePaymentInfo() is declared in the same ts file.

Please find the below code:

var RequestData={
    key: paymentRequest.key,
    txnid: paymentRequest.txnId,
    hash: paymentRequest.hash,
    amount: paymentRequest.amount,
    firstname: paymentRequest.firstName,
    email: paymentRequest.email,
    phone: paymentRequest.phone,
    productinfo: paymentRequest.productInfo,
    udf1: paymentRequest.udf1,
    surl: paymentRequest.sUrl,
    furl: paymentRequest.fUrl
    }
var Handlers={
        responseHandler: function(BOLT) {
               if (BOLT.response.txnStatus != "CANCEL") {
                this.updatePaymentInfo(BOLT.response);
               } 
               else {
                alert(BOLT.response);
               }
        return BOLT.response;
        },
        catchException: function(BOLT) {
          alert(BOLT.message);
        }
   }

    launchBOLT(paymentRequest) {
        bolt.launch(RequestData,Handlers);
    }

Solution

  • If you're trying to access a value outside the scope of the inner function, you should use arrow functions. Instead of:

    responseHandler: function(BOLT) {
        if (BOLT.response.txnStatus != "CANCEL") {
          this.updatePaymentInfo(BOLT.response);
        } else { alert(BOLT.response); }
        return BOLT.response;
      }
    ...
    

    use arrow functions so you can access to the outer scope this object:

    responseHandler: (BOLT) => {
        if (BOLT.response.txnStatus != "CANCEL") {
          this.updatePaymentInfo(BOLT.response);
        } else { alert(BOLT.response); }
        return BOLT.response;
      }
    ...
    

    Otherwise, the this will refers to the anonymous function itself, instead of referring to the class it's currently in.

    If by any chance, you're using ECMAScript 3 or earlier, you'll have to save this in a variable before using it inside your function because arrow functions didn't exist in those versions (as we are talking about Angular 9, I think this will hardly be the case):

    var _this = this;
    var Handlers = {
      responseHandler: function(BOLT) {
          if (BOLT.response.txnStatus != "CANCEL") {
            _this.updatePaymentInfo(BOLT.response);
          } else { alert(BOLT.response); }
          return BOLT.response;
        }
    ...