node.js - Stripe Angular 错误: Uncaught (in promise): TypeError: Cannot read property 'stripeService' of undefined

标签 node.js angular typescript promise stripe-payments

我目前正在尝试在我的 angular4 Nodejs 应用程序中实现 stripe,但是当我尝试通过处理与 stripe 相关的请求的服务将卡 token 发送到我的服务器时,我有点卡住了。这是我得到的代码:

stripe.component.html:

<form role="form" id="payment-form">
    <div id="card-element"></div>
    <div id="card-errors" role="alert"></div>
    <button type="submit" (click)="addCard()">Submit Payment</button>
</form>

stripe.component.ts:

import {Component, OnInit} from "@angular/core";
import {WindowRef} from "../social/windowRef";
import {StripeService} from "./stripe.service";

@Component({
    selector: "app-stripe",
    templateUrl: './stripe.component.html',
    styleUrls: ['./stripe.component.css']
})
export class StripeComponent implements OnInit {
    elements: any;
    stripe: any;
    style: any;
    card: any;

    constructor(private stripeService: StripeService){}


    ngOnInit() {
        this.initCardElement();
    }

    initCardElement(){
        this.stripe = WindowRef.get().Stripe("my-key");
        this.elements = this.stripe.elements();
        this.style =
            {
                base: {
                    color: '#32325d',
                    lineHeight: '24px',
                    fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
                    fontSmoothing: 'antialiased',
                    fontSize: '16px',
                    '::placeholder': {
                        color: '#aab7c4'
                    }
                },
                invalid: {
                    color: '#fa755a',
                    iconColor: '#fa755a'
                }
            };
        this.card = this.elements.create('card', {style: this.style});
        this.card.mount('#card-element');
    }


    addCard() {
        this.stripe.createToken(this.card)
            .then(function (result) {
                if (result.error) {
                    var errorElement = document.getElementById('card-errors');
                    errorElement.textContent = result.error.message;
                } else {
                    console.log(result.token);
                    this.stripeService.addCard(result.token)
                        .subscribe((response: Response) => {
                                console.log(response);
                            }
                        );
                }
            });
    }
}

我设法获取了 stripe 的卡 token ,但是当我尝试调用我的 stripeService 时,出现了此错误:

Error: Uncaught (in promise): TypeError: Cannot read property 'stripeService' of undefined

我知道 this.stripeService 未在此处定义,但我不明白如何解决此问题。

祝你有美好的一天:)

最佳答案

如果您想使用外部 this,请使用箭头函数。使用 function 声明的函数会创建一个新的 this,但此处未定义。

运行此示例以查看发生了什么:

class X {
  constructor(x) {
    this.x = x;
  }
  a() {
    (function () {
      console.log(this.x);
    })();
  }
  b() {
    (() => {
      console.log(this.x);
    })();
  }
}

let x = new X(10);
x.b();
x.a();

此处,b() 方法内的函数正确使用了外部 this,但 a() 方法有一个创建其自身的函数自己的 this 未定义并导致错误:

TypeError: Cannot read property 'x' of undefined

在您的示例中,您可以更改此设置:

addCard() {
    this.stripe.createToken(this.card)
        .then(function (result) {
            if (result.error) {
                var errorElement = document.getElementById('card-errors');
                errorElement.textContent = result.error.message;
            } else {
                console.log(result.token);
                this.stripeService.addCard(result.token)
                    .subscribe((response: Response) => {
                            console.log(response);
                        }
                    );
            }
        });
}

对此:

addCard() {
    this.stripe.createToken(this.card)
        .then((result) => {
            if (result.error) {
                var errorElement = document.getElementById('card-errors');
                errorElement.textContent = result.error.message;
            } else {
                console.log(result.token);
                this.stripeService.addCard(result.token)
                    .subscribe((response: Response) => {
                            console.log(response);
                        }
                    );
            }
        });
}

(未测试)

关于node.js - Stripe Angular 错误: Uncaught (in promise): TypeError: Cannot read property 'stripeService' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45147544/

相关文章:

node.js - 如何覆盖嵌套的 NPM 依赖版本?

javascript - fatal error : CALL_AND_RETRY_LAST Allocation failed — process out of memory

java - JHipster 中的复选框

angular - Set 仅指一种类型,但它被用作值 - WebStorm

javascript - 如何从 create-react-app 迁移到 typescript?

javascript - NodeJS vm.runInThisContext() 和缺少 __filename

google-app-engine - Angular 2 和 Google App Engine,设置基本 href,重新加载子路由失败,服务器端路由

angular - ionic 2 返回 {"__zone_symbol__state":null ,"__zone_symbol__value" :"cyprus"}

javascript - 链接函数没有被调用

node.js - 使用 npm 安装 node.js 模块时出错