2017-03-18 53 views
0

我遇到了Stripe Checkout和Angular2的問題。我使用token()函數將我的token.id發佈到服務器端,但Web控制檯返回「無法讀取屬性'post'of undefined」。Angular2條紋功能令牌()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

使用fat arrow您的功能像這樣

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

,如果您使用函數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是的,你是對的,我在解釋這個時候缺乏話語,但是我的邏輯和你一樣,順便說一句,謝謝你的措辭,在我的回答中對其他人的錯誤更新。謝謝 –