2016-06-15 8 views
1

私はAngular2とストライプの支払いを統合しています(実際にはイオンが、コードが同じである)Angular2ストライプ統合stripeResponseHandlerこの

にアクセスすることはできませんStripe.card.createTokenの呼び出しが成功し、トークン

を返しますがstripeResponseHandlerでいます非同期コールバックであるため、「this」変数にはアクセスできません。たとえば、私はthis.amount = 10を設定できません。私は呼び出すことができません。this._http.post

"this"変数にはどのようにアクセスできますか?私は、httpしようとしているあなただけの関数参照を渡すと、支払い

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'); 
    } 

答えて

0

を作るためのAPIにトークンと量を掲示し、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)); 
+0

優れ参照してください - 完璧に動作しています - ありがとう – user6231846

関連する問題