angular - 以 Angular 6 形式初始化 Square iframe 的问题

标签 angular typescript square

我在将 Square iframe 加载到我的表单时遇到问题。当我从导航栏导航到支付表单时,iframe 没有加载到我的输入字段中。加载它们的唯一方法是点击刷新我的付款表格。这是我的 payment.ts:

import { Component, OnInit, Input, EventEmitter, AfterViewInit } from '@angular/core';
import {AppService} from '../app.service';

declare var SqPaymentForm: any;

@Component({
  selector: 'app-payment',
  templateUrl: './payment.component.html',
  styleUrls: ['./payment.component.css']
})
export class PaymentComponent implements OnInit, AfterViewInit  {

  constructor(private appService: AppService) { }
  paymentForm: any ;
  ngOnInit() {
   this.squarePaymentFunction();
  }
  ngAfterViewInit(): void  {}

  squarePaymentFunction() {
    let vm;
    vm = this;
    // this.calculatePayment();
    const applicationId = '********';

    // Set the location ID
    const locationId = '*********';
    this.paymentForm = new SqPaymentForm({

      // Initialize the payment form elements
      applicationId: applicationId,
      locationId: locationId,
      inputClass: 'sq-input',

      // Customize the CSS for SqPaymentForm iframe elements
      inputStyles: [{
        fontSize: '.9em'
      }],

      // Initialize the credit card placeholders
      cardNumber: {
        elementId: 'sq-card-number',
        placeholder: '•••• •••• •••• ••••'
      },
      cvv: {
        elementId: 'sq-cvv',
        placeholder: 'CVV'
      },
      expirationDate: {
        elementId: 'sq-expiration-date',
        placeholder: 'MM/YY'
      },
      postalCode: {
        elementId: 'sq-postal-code'
      },
      // SqPaymentForm callback functions
      callbacks: {

        /*
         * callback function: methodsSupported
         * Triggered when: the page is loaded.
         */
        methodsSupported: function (methods) {
        },

        /*
         * callback function: createPaymentRequest
         * Triggered when: a digital wallet payment button is clicked.
         */
        createPaymentRequest: function () {

          let paymentRequestJson;
          return paymentRequestJson;

        },

        /*
         * callback function: cardNonceResponseReceived
         * Triggered when: SqPaymentForm completes a card nonce request
         */
        cardNonceResponseReceived: function (errors, nonce, cardData)  {
          if (errors) {
            // Log errors from nonce generation to the Javascript console
            console.log('Encountered errors:');
            errors.forEach(function(error) {
              console.log('  ' + error.message);
            });

            return;
          }

          alert('Nonce received: ' + nonce); /* FOR TESTING ONLY */

          // Assign the nonce value to the hidden form field
          // document.getElementById('card-nonce').value = nonce;
          // needs to be extracted from the
          (<HTMLInputElement>document.getElementById('card-nonce')).value = nonce; // casting so .value will work

          let amount = (<HTMLInputElement>document.getElementById('amountToPay')).value;

          // POST the nonce form to the payment processing page
          // (<HTMLFormElement>document.getElementById('nonce-form')).submit();
          vm.sendSqPayment({'nonce': nonce, 'amountToPay': amount});
        },

        /*
         * callback function: unsupportedBrowserDetected
         * Triggered when: the page loads and an unsupported browser is detected
         */
        unsupportedBrowserDetected: function() {
          alert('Your browser seems to be unsupported for card processing. Please try a different browser.');
        },

        /*
         * callback function: inputEventReceived
         * Triggered when: visitors interact with SqPaymentForm iframe elements.
         */
        inputEventReceived: function(inputEvent) {
          switch (inputEvent.eventType) {
            case 'focusClassAdded':
              /* HANDLE AS DESIRED */
              break;
            case 'focusClassRemoved':
              /* HANDLE AS DESIRED */
              break;
            case 'errorClassAdded':
              document.getElementById('error').innerHTML = 'Please fix card information errors before continuing.';
              /* HANDLE AS DESIRED */
              break;
            case 'errorClassRemoved':
              document.getElementById('error').style.display = 'none';
              /* HANDLE AS DESIRED */
              break;
            case 'cardBrandChanged':
              /* HANDLE AS DESIRED */
              break;
            case 'postalCodeChanged':
              /* HANDLE AS DESIRED */
              break;
          }
        },

        /*
         * callback function: paymentFormLoaded
         * Triggered when: SqPaymentForm is fully loaded
         */
        paymentFormLoaded: function() {
          /* HANDLE AS DESIRED */
          console.log('The form loaded!');
        }
      }
    });
  }

  requestCardNonce(event) {


    // Request a nonce from the SqPaymentForm object
    this.paymentForm.requestCardNonce();
  }
  sendSqPayment(data) {
    this.appService.sendPayment(data).subscribe((data) => {
        if (data.success) {
          console.log('Data success');
        }
        // console.log('data', data);
      },
    );
  }
}

我在我的 app.routing.ts 中使用 Routes 和 RouterModlue 设置了路由

最佳答案

首先设置autobuild为false

squarePaymentFunction() {
    let vm;
    vm = this;

    this.paymentForm = new SqPaymentForm({

      // Initialize the payment form elements
      applicationId: applicationId,
      locationId: locationId,
      inputClass: 'sq-input',
      autoBuild : false,
)};

然后我创建了一个局部变量并设置为false

formLoaded: boolean =  false;

接下来,我创建了一个函数来检查表单是否已构建并将其添加到 ngOnInit() 中:

loadPaymentForm() {
    if (this.formLoaded === false) {
      this.paymentForm.build();
      this.formLoaded = true;
    }
}

最后一步是将我的功能添加到输入字段

<input id="property_name" formControlName="property_name"  (focus)="loadPaymentForm()" (input)="checkInputError()" type="text" class="form-control" name="property_name" required/>

这不是最好的方法,但它很有效。

关于angular - 以 Angular 6 形式初始化 Square iframe 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53402215/

相关文章:

square - Android 中的 Dagger 作用域

Android Picasso 克隆但无法运行示例项目,未找到 gradle 文件

javascript - 在动画进行时暂停调度 NgRx Action

html - 溢出换行未应用于文本

javascript - 如何使用 javascript 对象中的构造函数来仅使用 `this` 中的属性?

javascript - 返回值未在花药返回有效负载中拾取

typescript - 将 eslint 与 typescript 一起使用 - 无法解析模块的路径

javascript - 数组中的平方值 (JavaScript) 加上浮点错误

javascript - [] vs [{...}] 在浏览器工具中,同时具有相同的对象

angular - 检测 @Input 属性 angular 4 的内部变化