簡體   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