【问题标题】:stripe angular Error: Uncaught (in promise): TypeError: Cannot read property 'stripeService' of undefined条纹角度错误:未捕获(承诺):TypeError:无法读取未定义的属性“stripeService”
【发布时间】:2017-12-22 04:28:02
【问题描述】:

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

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);
                            }
                        );
                }
            });
    }
}

我设法获得了条纹的卡令牌,但是当我尝试调用我的 stripeService 时,我收到了这个错误:

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

我知道这里没有定义this.stripeService,但我不明白如何解决这个问题。

祝你有美好的一天:)

【问题讨论】:

  • 使用箭头功能,你失去了上下文。 function (result){ /* some code / } to (result) => { / some code */ }

标签: node.js angular typescript promise stripe-payments


【解决方案1】:

当您使用function 关键字定义匿名或命名函数时,它会创建一个新范围,this 关键字指向新创建函数的范围。你想要的是引用addCard函数的作用域

有几种方法可以做到这一点:

首先最好的方法是使用不创建新范围的 ES6 箭头函数 例如:

this.stripe.createToken(this.card)
.then((result) => { 
    console.log(this.stripeService); // it will be defined here
})

第二个选项是存储对addCard范围的引用:

let that = this;
this.stripe.createToken(this.card)
.then((result) => { 
    console.log(that.stripeService); // it will be defined here
})

【讨论】:

    【解决方案2】:

    如果您想使用外部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);
                            }
                        );
                }
            });
    }
    

    (未测试)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多