【问题标题】:How to call a component function from inside a callback for angular 2 + (razorpay)?如何从 angular 2 + (razorpay) 的回调内部调用组件函数?
【发布时间】:2020-02-15 14:52:45
【问题描述】:

所以我试图从支付应用程序razorpay 的api 的回调响应中调用一个函数。我不能使用“this”来调用组件内的函数,因为它位于处理程序的嵌套函数中。如何从回调“handler”中调用函数handle_response()?

myComponent.ts

var options = {
    "amount": 100, 
    "name": "ABC",
    "currency": "USD",
    "handler": function (response){
        console.log(response);//this returns the expected value
        this.handle_response(response); //does not work as cannot identify 'this'
    }
};
var rzp1 = new this.winRef.nativeWindow.Razorpay(options);
rzp1.open();

handle_response(_response){....}

【问题讨论】:

    标签: angular callback razorpay


    【解决方案1】:

    您想使用函数的bind 方法或打字稿中的粗箭头语法。可以是:

    let options = {
        "amount": 100, 
        "name": "ABC",
        "currency": "USD",
        "handler": function (response){
            console.log(response);//this returns the expected value
            this.handle_response(response); //does not work as cannot identify 'this'
        }.bind(this)
    };
    let rzp1 = new this.winRef.nativeWindow.Razorpay(options);
    rzp1.open();
    
    handle_response(_response){....}
    

    您可以使用 javascript 箭头功能。阅读更多关于箭头函数here

    let options = {
        "amount": 100, 
        "name": "ABC",
        "currency": "USD",
        "handler": (response) => {
            console.log(response);//this returns the expected value
            this.handle_response(response); //does not work as cannot identify 'this'
        }
    };
    let rzp1 = new this.winRef.nativeWindow.Razorpay(options);
    rzp1.open();
    
    handle_response(_response){....}
    

    【讨论】:

      【解决方案2】:

      您可以将 this 绑定为选项之外的局部变量,然后像使用局部变量一样调用 this:-

      var newThis=this;
          var options = {
          "amount": 100, 
          "name": "ABC",
          "currency": "USD",
          "handler": function (response){
              console.log(response);//this returns the expected value
              newThis.handle_response(response); // 'this' works as new this
          }
      };
      var rzp1 = new this.winRef.nativeWindow.Razorpay(options);
      rzp1.open();
      

      【讨论】:

        猜你喜欢
        • 2018-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-20
        • 2017-06-17
        • 1970-01-01
        • 1970-01-01
        • 2011-04-06
        相关资源
        最近更新 更多