Angular中PayPal回调调用TypeScript函数时planService未定义的解决方法
解决Angular中PayPal回调里调用TypeScript服务的问题
问题根源是你用普通function定义onApprove回调时,this的指向不是Angular组件实例,而是PayPal按钮的上下文,所以planService会变成undefined。以下是三种可行的修复方案:
方案1:使用箭头函数(推荐)
箭头函数会继承外层作用域的this(也就是你的组件实例),直接修改onApprove的定义方式即可:
(window as any).paypal.Buttons({ createSubscription: function (data, actions) { return actions.subscription.create({ 'plan_id': 'XXXXX' }); }, onApprove: (data, actions) => { this.planService.subscribe(1, data.subscriptionID).subscribe(x => alert('SUCCESS')); } }).render('#paypal-button-container');
方案2:提前保存组件实例的this
在创建PayPal按钮前,把组件的this存到变量里,回调里用这个变量代替this:
const componentInstance = this; (window as any).paypal.Buttons({ createSubscription: function (data, actions) { return actions.subscription.create({ 'plan_id': 'XXXXX' }); }, onApprove: function (data, actions) { componentInstance.planService.subscribe(1, data.subscriptionID).subscribe(x => alert('SUCCESS')); } }).render('#paypal-button-container');
方案3:用bind绑定this
通过bind方法把回调函数的this强制绑定到组件实例:
(window as any).paypal.Buttons({ createSubscription: function (data, actions) { return actions.subscription.create({ 'plan_id': 'XXXXX' }); }, onApprove: function (data, actions) { this.planService.subscribe(1, data.subscriptionID).subscribe(x => alert('SUCCESS')); }.bind(this) }).render('#paypal-button-container');
内容的提问来源于stack exchange,提问作者Naner
相关产品推荐
相关产品推荐

