I've got a problem with Stripe Checkout and Angular2. I use the token() function to post my token.id to the server side but the web console return me "Cannot read property 'post' of undefined".
But I can do http.post in others functions in this component and it works.
Can you help me ?
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>
Use fat arrow
for your function like this
token: (token: any)=> {...}
if you are using function like this
token: (token: any)=> {
//here `this` will work fine, scope of this will present here
}
but in case of normal method like this
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.
}
for more info refer here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.