Home > Enterprise >  Access TypeScript function from Javascript callback Angular
Access TypeScript function from Javascript callback Angular

Time:11-17

I'm successfully rendering a Paypal button in Angular by doing the following:

 (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'));
        }
    }).render('#paypal-button-container');

Everything works as expected, but planService is undefined when the callback is called, which I understand why, but don't know how to fix. How do I call a Typescript function from the Javascript callback? Any suggestions, please?

CodePudding user response:

Your implementation lacks the this reference, thus planService is undefined in the regarding context. Use an arrow function to bind the current this reference to the function:

 (window as any).paypal.Buttons({
        createSubscription: function (data, actions) {
            return actions.subscription.create({
                'plan_id': 'XXXXX'
            });
        },
        onApprove: (data, actions) => { // arrow function to bind "this"
            this.planService.subscribe(1, data.subscriptionID).subscribe(x => alert('SUCCESS'));
        }
    }).render('#paypal-button-container');

One more thing to note: You may want to check if this.planService (assumingly an Observable) runs inside the angular zone. If it does not (because it was triggered by a third party implementation (paypal), you may notice that templates do not update accordingly (changes not being picked up by change-detection or change-detection not running as expected).

  • Related