繁体   English   中英

如何从 angular 2 + (razorpay) 的回调中调用组件 function?

[英]How to call a component function from inside a callback for angular 2 + (razorpay)?

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

我的组件.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){....}

您想使用 function 的bind方法或 typescript 中的粗箭头语法。 它可以是:

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 箭头 function。 在此处阅读有关箭头 function 的更多信息

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){....}

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

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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM