Calling function typescript in a javascript function

Asked

Viewed 773 times

0

I have a function that when you click on a button it creates a token from the user information.

<button ion-button (click)="onTapBuyCart()"></ion-button> 

But when I try to call this.cartPay() function; inside Mercadopago.createToken(javascript function), this error happens.

this.cartPay is not a function

onTapBuyCart() {
            let form = document.querySelector('#form');
            console.log(form);
            Mercadopago.createToken(form, function (status, response) {
                this.hashCartao = response.id;
                console.log(this.hashCartao + ' HASH');
            this.cartPay();
            });
        }
    }

   public cartPay() {
        console.log(this.hashCartao);
        let loader = this._loaderCtrl.create({
            content: "Validando compra, aguarde um momento"
        });
        loader.present();
        this._cartProvider
            .payCart(
                this.formaPagamentoSelecionada,
                this.nmCartao,
                this.titular,
                this.formaVezes,
                this.hashCartao
            )
            .subscribe(
                (cart: any) => {
                    loader.dismiss();
                    this.navCtrl.setRoot(SucessCartPage, { cart });
                },
                error1 => {
                    var arr = Object.keys(error1.error.errors).map(key => ({
                        type: key,
                        value: error1.error.errors[key]
                    }));
                    this.errorSubscribe = error1.error.errors;
                    this.errorJson = arr;
                    console.log(error1);
                    loader.dismiss();
                    let toast = this._toastCtrl.create({ message: "Ocorreu um erro" , duration:3000 });
                    toast.present();
                }
            );
    }

Is there any way I can call this typescript function inside javascript without error? Thank you very much for your attention.

1 answer

1


When you use a callback function (that function you pass in createToken), within a method, you lose the reference of this, which happens to be that of the Mercadopago object.

an easy way to solve this is to save this in a variable, before calling Mercadopago.

Ex: Let self = this;

Or also use Arrow Function in place of common function

Browser other questions tagged

You are not signed in. Login or sign up in order to post.