【问题标题】:How to call / access an Angular method from third party api function? (integrating ApplePay into Angular website)如何从第三方 api 函数调用/访问 Angular 方法? (将 ApplePay 集成到 Angular 网站中)
【发布时间】:2021-06-29 02:56:34
【问题描述】:

我是 Angular 的新手,这是我的问题:

我正在尝试使用 Angular11 将 Apple Pay 集成到网站中。 现在我已经安装了一个 npm 包,其中包含 Apple Pay JS (@types/applepayjs) 的类型定义。但是现在我无法从这个 api-function 访问我的函数。

我在 api-function 中的所有函数或变量都变为“任何”类型并显示未定义。我必须将数据发送到后端服务器以与 Apple 通信并从服务器获取返回消息。我想知道是因为范围原因还是语言原因。

我可以从第三方定义函数调用我的函数或通过构造函数访问依赖注入服务吗?有什么解决办法或建议吗?

请帮忙,非常感谢。

这是我的代码。 组件.ts

        
    export class ApplepayComponent {
        
        constructior(
            private service: ApplepayService
        ){}

        // ...........
        
        doApplePay(){
            
            const paymentRequest: ApplePayJs.ApplePayPaymentRequest = {
                countryCode: 'US',
                currencyCode: 'USD',
                supportedNetworks: ['visa', 'masterCard'],
                merchantCapabilities: ['supports3DS'],
                total: { label: 'My Store', amount: '10.00' }                
            }

            const session  = new ApplePaySession(2, paymentRequest);
            session.onvalidatemerchant = function(event) {
                const validationURL = event.validationURL;

                // here is my question
                // I want to call my service to communicate with back-end server
                this.service.validateApplePay(this.secretKey).then((result) =>{
                    const merchantValidation = result.DATA.RETURN_MSG;
                    // and if complete, call 
                    session.completeMerchantValidation(result.RETURN_MSG)
                });
                
            }
        }

        
    }

service.ts

export class ApplepayService {
        constructior(
            private service: ApiService
        ){}
        async validateApplePay(secretKey: string):Promise<any>{
            const res = await this.apiService.valdateApplepay({
                SECRET_KEY: secretKey
            }).toPromise();
            return res;
        }
}

【问题讨论】:

  • 你想如何运行它?在网络浏览器上?还是在应用中?
  • @Apps 我尝试使用 Angular 和 Spring Boot 在网络上运行它。
  • 我认为这不适用于非 iOS 或 MacOS 环境。即使您使方法调用正常工作
  • 是的。我认为我应该首先检测用户的浏览器以检查 Apple Pay 的可用性。

标签: angular typescript function applepay


【解决方案1】:

这是因为您的上下文变量this 在您的api-function 中不可用。试试其中一种。

将您的function 转换为fat arrow function

session.onvalidatemerchant = (event) => { ... }

或者,将this 传递给另一个变量

var self = this;
session.onvalidatemerchant = function(event) {
    self.(...)
}

Read more

【讨论】:

  • 对我帮助很大。我会试试这个方法。非常感谢!!
  • 很高兴知道我能帮上忙。更重要的是,这是一个JavaScript 问题而不是Angular 问题。我建议您阅读更多关于 this 关键字的信息。你可以从这里开始:dev.to/vyasriday/what-the-heck-is-this-in-javascript-37n1
猜你喜欢
  • 2023-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-15
  • 1970-01-01
  • 2020-05-13
相关资源
最近更新 更多