首页 > 解决方案 > 无法访问变量

问题描述

pay(amount){
    var handler = (<any>window).StripeCheckout.configure({
      key: 'public stripe key',
      locale: 'auto',
      token: function (token: any) {
        // You can access the token ID with `token.id`.
        // Get the token ID to your server-side code for use.
        this.stripeToken = token.id;
      }
    });

    console.log('token is ' + this.stripeToken);

    handler.open({
      name: 'Demo Site',
      description: '2 widgets',
      amount: amount * 100
    });

    console.log(this.stripeToken + ' again')
  }

由于某种原因,我无法访问令牌函数之外的 this.stripeToken 变量。当我尝试使用 'token is' + stripeToken 或 this.stripetoken + 'again' 来 console.log() 时,我只是得到一个未定义的变量。条带变量声明如下: public stripeToken: any; 在 component.ts 页面的顶部,这是其中的一部分。请帮忙。

标签: typescriptstripe-payments

解决方案


由于某种原因,我无法访问令牌函数之外的 this.stripeToken 变量。

那是因为它还不存在。将来某个时候会异步调用令牌函数,但您的日志语句会立即发生。如果您有需要使用令牌的代码,则应将其放入回调函数中。

var handler = (<any>window).StripeCheckout.configure({
  key: 'pk_test_51HX4yUDEnGCSjwlXYRIFs3Wj9fFXw8DW7kLUacKFKPIcC0P96E6C4I9kVku5brUOGR33O2KKH6NkfIawr3oo11eU00eL9q8lAk',
  locale: 'auto',
  token: function (token: any) {
    // Put your code that uses the token here
  }
});

推荐阅读