Angular2 Stripe函数token()http.post undefined

时间:2017-03-18 11:52:48

标签: javascript angular http post

我遇到Stripe Checkout和Angular2的问题。我使用token()函数将我的token.id发布到服务器端,但是Web控制台返回“无法读取未定义的属性'帖子”。

但我可以在此组件的其他函数中执行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 个答案:

答案 0 :(得分:1)

使用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.
}

了解更多信息,请参阅此处