在 Angular 4 中处理 Paypal onAuthorize 回调

Processing Paypal onAuthorize callback in Angular 4

我可以在Angular 4 应用程序中成功加载checkout.js,渲染Paypal 按钮,出现新的window,我确认付款,付款已处理但我没有知道如何设置 onAuthorize 回调来处理 Angular 4 中的响应(比如显示成功并将支付记录存储到 MongoDb)。这是我的代码。我可以看到包含付款响应的第一个 console.log,但我无法访问该组件的范围,因此在执行第一个 console.log 之后什么也没有执行。我在控制台中没有错误。即使 console.log("successful!") 也不会被处理。

onAuthorize: (data, actions) => {
            return actions.payment.execute().then(function(payment) {
                console.log("response = " + JSON.stringify(payment));
                this._alertService.success("The extension of subscription was succesfull!");
                this.user.contracts.push({
                        "acquired": new Date(payment.create_time), 
                        "price": payment.transactions[0].amount.total, 
                        "expires": new Date(this.user.expires.getFullYear()+this.selectedAccountExtensionOption.addedYears, this.user.expires.getMonth(), this.user.expires.getDate()) 
                        });
                console.log("successful!");     

            });
        },

问题是上下文 (this) 在回调中不可用。最好的解决方案是按照 answer to this question

中的说明绑定 this

替代解决方案是在 PayPal 回调中发出自定义事件(文档 here

let event = new CustomEvent('dosomething', { data: "some data" });

然后在您的组件中捕获此事件。文档 here.

@HostListener('dosomething') 
onDoSomething(data) {
 console.log(data)
 // your rest of the implementation
}