You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 18:45:47