简体   繁体   English

第一次单击事件后,Stripe 客户端集成不会重定向

[英]Stripe client integration doesn't redirect after first click event

I am integrating Stripe client only integration in Angular2+ project following these steps:我按照以下步骤将 Stripe 客户端集成到 Angular2+ 项目中:

Stripe docs条纹文档

The onClick implementation is working fine, but for some reason the click event redirects me only when I clicked twice, even though the console.log is working on the first one. onClick 实现工作正常,但由于某种原因,单击事件仅在我单击两次时重定向我,即使 console.log 正在处理第一个。

HTML HTML

<button id="checkout-button" role="link" (click)="onClick($event)">
    Checkout
</button>

.ts .ts

onClick() {
    var checkoutButton = document.getElementById('checkout-button-sku_...');
    checkoutButton.addEventListener('click', function () {
        stripe.redirectToCheckout({
            items: [{ sku: 'sku_...', quantity: 1 }],
            successUrl: 'https://your-website.com/success',
            cancelUrl: 'https://your-website.com/canceled',
        })
            .then(function (result) {
                if (result.error) {
                    var displayError = document.getElementById('error-message');
                    displayError.textContent = result.error.message;
                }
            });
    });
}

It happens because at the first click, you are adding addEventListener .发生这种情况是因为在第一次单击时,您添加的是addEventListener So when you click the second time, then your event handler is run.因此,当您第二次单击时,您的事件处理程序就会运行。

In addition, it is not good to use document.getElementById .另外,使用document.getElementById也不好。 You can use TemplateRef :您可以使用TemplateRef

<button      
  role="link"
  (click)="onClick()"
  #checkout_button
>
  CheckoutButton Sku
</button>

TypeScript:打字稿:

@ViewChild('checkout_button') myEl: ElementRef;

constructor() {
}

ngAfterViewInit() {
  console.log(this.myEl.nativeElement);
}
checkoutButton.addEventListener('click', function () {

You do not need to bind another event handler.您不需要绑定另一个事件处理程序。

(click)="onClick($event)"

This part binds an event listener to the button.这部分将事件侦听器绑定到按钮。 In onClick you do an another bind every time when button is clicked.在 onClick 中,每次单击按钮时都会执行另一个绑定。 This is why it works only for the second time.这就是它只第二次工作的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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