Angular中如何在Razorpay的handler方法内访问组件实例变量
报错根因
handler回调使用普通function声明时,this会在函数执行时被Razorpay内部绑定到options配置对象上,不会指向Angular组件实例,自然访问不到实例上的days属性。另外原代码直接用类名SubscriptionPlanComponent调用update_payment_to_paid的写法也有问题:该方法是组件实例方法,不是类的静态方法,不能直接通过类名调用。
修复方案
优先使用第一种方案,符合Angular+TS的常规编码习惯:
方案1:将回调改为箭头函数(推荐)
箭头函数没有独立的this上下文,会直接继承定义位置外层(即组件类实例)的this指向,修改后的代码如下:
days: any; options = { "key": "rzp_test_1234567890", // 从Dashboard生成的Key ID "amount": "", // 金额单位为货币最小子单位,默认货币INR场景下50000代表50000派沙 "currency": "INR", "name": "Acme Corp", "description": "Test Transaction", "image": "https://example.com/your_logo", "order_id": "", // 传入第一步接口返回的order id // 改为箭头函数 "handler": (response: any) => { // 直接通过this访问组件实例的方法和属性 this.update_payment_to_paid(response, this.days); }, "prefill": { "name": "Gaurav Kumar", "email": "gaurav.kumar@example.com", "contact": "9999999999" }, "notes": { "address": "Razorpay Corporate Office" }, "theme": { "color": "#3399cc" } }; update_payment_to_paid(resp: any, days: any) { // 原有支付状态更新逻辑 }
方案2:提前缓存组件实例引用
如果不修改回调的函数声明形式,可以在定义options前提前保存组件实例的this引用,回调中通过缓存的变量访问实例成员:
days: any; // 提前缓存组件实例this const componentRef = this; options = { // key、amount、currency等其余配置保持不变 "handler": function (response:any){ componentRef.update_payment_to_paid(response, componentRef.days); }, // prefill、notes、theme等其余配置和原有代码一致 };
内容的提问来源于stack exchange,提问作者Amol_G
相关产品推荐
相关产品推荐

