我在使用 Stripe Checkout 和 Angular2 时遇到问题。我使用 token() 函数将 token.id 发布到服务器端,但 Web 控制台返回“无法读取未定义的属性‘post’”。
但是我可以在这个组件的其他函数中执行 http.post 并且它可以工作。
你能帮我吗?
组件.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
});
}
组件.html
<button (click)="this.cartService.openCheckout()">Stripe</button>
最佳答案
使用 fat arrow
来实现这样的函数
token: (token: any)=> {...}
如果你正在使用这样的函数
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.
}
有关更多信息,请参阅此处
关于javascript - Angular2 Stripe 函数 token() http.post 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42874042/