簡體   English   中英

Angular2 Stripe函數token()http.post未定義

[英]Angular2 Stripe function token() http.post undefined

我遇到了Stripe Checkout和Angular2的問題。 我使用token()函數將我的token.id發布到服務器端,但Web控制台向我返回“無法讀取未定義的屬性'post'”。

但是我可以在此組件的其他函數中執行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>

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

有關更多信息,請參見此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM