javascript - Angular2 Stripe 函数 token() http.post 未定义

标签 javascript angular http post

我在使用 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/

相关文章:

javascript - 如何在 ASP.NET MVC 中从 JSON 呈现 FullCalendar 中的事件?

javascript - 断言一个组件只能用作另一个组件的子组件

javascript - 如何在 Angular 中读取在线 html 文档并转换为字符串

javascript - Angular 路由器中全局可用的 url 参数

http - 如何将自定义 HTTP 请求 header 添加到 Thymeleaf 生成的表单或链接?

java - HttpURLConnection返回的InputStream中的数据在读取之前存储在哪里?

http - 使用具有适当名称的 Powershell 从 http 下载多个文件

javascript - 在普通 VueJS 项目中使用 Typescript 函数

javascript - 单击以显示更多内容 - 2 列

javascript - 由于内容不同,Meteor 重复模板