Angular2 Stripe集成stripeResponseHandler无法访问此

时间:2016-06-15 18:05:00

标签: ionic-framework angular payment

我将Stripe付款与Angular2集成(实际上是Ionic,但代码是相同的)

Stripe.card.createToken的调用成功并返回一个令牌

但是在stripeResponseHandler这是一个异步回调,我无法访问任何"这个"变量。例如,我无法设置this.amount = 10,我无法调用this._http.post

我怎样才能访问"这个"变量?我试图将令牌和金额发送到API以进行付款

  constructor(private _navController: NavController,
    private _http: Http) {   }

  submitPayment() {
    Stripe.setPublishableKey(this.key);
    this.card = new Card();
    this.card.number = this.cardNumber;
    this.card.cvc = this.cardCVC;
    this.card.exp_month = this.cardExpMonth;
    this.card.exp_year = this.cardExpYear;
    this.card.address_zip = this.cardAddressZip;

    try {
      Stripe.card.createToken(this.card, this.stripeResponseHandler);
    }
    catch (e) {
      alert(e.message);
    }

    // Prevent the form from being submitted:
    return false;   
  }

  stripeResponseHandler(status, response) {

    if (response.error) { // Problem!
      alert(response.error);

    } else { // Token was created!

      // Get the token ID:
      alert(response.id);

      try {

        this.amount = 10;

        let payment = new Payment();
        payment.token = response.id;
        payment.amount = this.amount;

        let body = JSON.stringify(payment);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        this._http.post(this.url, body, options)
            .map(res => res.json())
            .catch(this.handleError);
      }
      catch (e) {
        alert(e.message);
      }

    }   
  }

  handleError(error: Response) {
    // may send the error to some remote logging infrastructure
    // instead of just logging it to the console
    console.error(error);
    alert('error' + error.text + " " + error.statusText);
    return Observable.throw(error.json().error || 'Server error');   
  }

1 个答案:

答案 0 :(得分:1)

如果您只是传递函数引用,那么JavaScript不会保留this引用。你必须明确地处理这个问题:

而不是

Stripe.card.createToken(this.card, this.stripeResponseHandler);

使用

Stripe.card.createToken(this.card, (status, person) => this.stripeResponseHandler(status, person));

另见https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Stripe.card.createToken(this.card, this.stripeResponseHandler.bind(this));