简体   繁体   中英

Access TypeScript function from Javascript callback Angular

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?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM