2017-03-18 7 views
0

Stripe CheckoutとAngular2に問題があります。私はトークン()関数を使用してtoken.idをサーバー側にポストしますが、Webコンソールは "未定義のプロパティ 'post'を読み取れません。Angular2 Stripe function token()http.post undefined

しかし、私はこのコンポーネントの他の機能でhttp.postを実行することができ、動作します。

私を助けることができますか?

component.ts

import {Injectable} from '@angular/core'; 
import {ToastOptions} from "ng2-toasty"; 
import {Http, Response, Headers, RequestOptions} from "@angular/http"; 
import {Observable} from "rxjs"; 

@Injectable() 
export class CartService { 

cart: any = []; 

constructor(public http: Http) { } 

openCheckout() { 
    var handler = (<any>window).StripeCheckout.configure({ 
     key: 'pk_test_stripe', 
     locale: 'auto', 
     token: function (token: any) { 

      alert(token.id); //This work ! 

      let client = { 
       // client JSON object 
      }; 

      //Cannot read property 'post' of undefined 
      this.http.post('PHP script URL', { // This doesn't work ! 
       products: this.cart, 
       client: client, 
       stripeToken: token 
      }).subscribe(data => { 
        console.log(data); 
       }, error => { 
        console.log("Oooops!"); 
       }); 
     } 
    }); 

    handler.open({ 
     name: 'Site demo', 
     description: 'Commande', 
     currency: 'chf', 
     panelLabel: 'Payer {{amount}}', 
     amount: 24500 
    }); 

} 

component.html

<button (click)="this.cartService.openCheckout()">Stripe</button> 

答えて

1

この

token: (token: any)=> {...} 

のようなあなたのための機能を使用するfat arrowあなたは関数Lを使用している場合、 IKEこの

token: (token: any)=> { 
    //here `this` will work fine, scope of this will present here 

} 

が、詳細はこの

token: function (token: any) { 
    // **this** won't be undefined here but it will refer to this (token) functions instance. The reason why OP is getting undefined is that it tries to select this.http which that functions instance does not have. 
} 

のような通常の方法の場合には、ここで

+0

を参照してください。ありがとうございました、それが動作します! –

+0

'this'は、トークン関数インスタンスを参照する関数の下で' undefined 'になりません。 OPが 'undefined 'になっているのは、その関数インスタンスにはないthis.httpを選択しようとするためです。 – echonax

+1

@echonaxはい、あなたは正しいです、私はこれを説明しながら言葉が不足していますが、私のロジックはあなたと同じでした。言葉遣いに感謝しています。ありがとう –

関連する問題