【问题标题】:ScriptJs: How to access variable after dynamically loading script?ScriptJs:动态加载脚本后如何访问变量?
【发布时间】:2023-03-04 02:31:01
【问题描述】:

我正在使用 script.js 动态加载 Paypal 客户端按钮,作为 Angular7 PaypalPaymentController 的一部分。我的组件代码如下:

import {Configuration, Procedure} from '../models';
import {get } from 'scriptjs';

@Component({
   ...
})
export class PaymentComponent implements OnInit {
  @Input() configuration: Configuration;
  @Input() procedure: Procedure;

  constructor() {
  }

  ngOnInit() {
    get(`https://www.paypal.com/sdk/js?client-id=${this.configuration.paypalClientId}&currency=${this.configuration.currency}`, () => {
      paypal.Buttons({  // <<<<<<<<<<<<<<<<<<<<<<<<<<<<< compiler error here
        // set up the transaction
        createOrder: this.createOrder,
        // finalize the transaction
        onApprove: this.onApprove
      }).render('#paypal-button-container');
    });
  }

  ...
}

执行scriptjsget 后如何访问动态加载脚本中定义的paypal 变量?否则我会收到 TS 编译器错误...

ERROR in src/app/payment/payment.component.ts(24,7): error TS2304: Cannot find name 'paypal'.

更新:完整的 Paypal 客户端示例如下(从那里复制粘贴):

<!DOCTYPE html>

<head>
    <!-- Add meta tags for mobile and IE -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
</head>

<body>
    <!-- Set up a container element for the button -->
    <div id="paypal-button-container"></div>

    <!-- Include the PayPal JavaScript SDK -->
    <script src="https://www.paypal.com/sdk/js?client-id=sb&currency=USD"></script>

    <script>
        // Render the PayPal button into #paypal-button-container
        paypal.Buttons({

            // Set up the transaction
            createOrder: function(data, actions) {
                return actions.order.create({
                    purchase_units: [{
                        amount: {
                            value: '0.01'
                        }
                    }]
                });
            },

            // Finalize the transaction
            onApprove: function(data, actions) {
                return actions.order.capture().then(function(details) {
                    // Show a success message to the buyer
                    alert('Transaction completed by ' + details.payer.name.given_name + '!');
                });
            }


        }).render('#paypal-button-container');
    </script>
</body>

【问题讨论】:

    标签: javascript angular typescript paypal angular7


    【解决方案1】:

    不知道您是如何设置环境的。我猜你也必须导入PayPal rest sdk。打字稿也有@types

    【讨论】:

    • 谢谢!动态get调用中的URL是Paypal SDK的导入。
    • 抱歉,没注意到。无论如何,ts 编译器不会知道paypal。 @types 可以提供帮助。
    【解决方案2】:

    只需在导入后添加以下行:

    declare let paypal: any;
    

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 1970-01-01
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 2011-02-13
      • 2011-05-22
      • 1970-01-01
      • 2015-01-17
      相关资源
      最近更新 更多