Search code examples
javascriptangularjsasynchronousangular-promiseionic-v1

Adapt External Asynchronous JavaScript API to AngularJS Framework


I have been trying to adapt an API's JavaScript code for receiving a payment token, but I can't find a way to create a function that runs the code. The API's original example works great, but I just can't convert the code into a reusable function. I tried different approaches but I'm always getting the same error:

TypeError: $scope.token is not a function

I'm using this code inside an Ionic app. Please help me, I can't find a solution.

API's original example:

$gn.ready(function(checkout) {
 
  var callback = function(error, response) {
    if(error) {
      // Error
      console.error(error);
    } else {
      // Success
      console.log(response);
    }
  };
 
  checkout.getPaymentToken({
    brand: 'visa', 
    number: '4012001038443335', 
    cvv: '123', 
    expiration_month: '05',
    expiration_year: '2018'
  }, callback);
 
});

My code:

$gn.ready(function(checkout) {

  $scope.token = function(b,n,c,m,y) {

    var callback = function(error, response) {

      if(error) {
        // Trata o erro ocorrido
        console.error(error);
      } else {
        // Trata a resposta
        console.log(response.data.payment_token);

      }
    };

    checkout.getPaymentToken({
      brand: b, // bandeira do cartão
      number: n, // número do cartão
      cvv: c, // código de segurança
      expiration_month: m, // mês de vencimento
      expiration_year: y // ano de vencimento
    }, callback);

  };

});


Solution

  • Put the $gn asynchronous API in a service:

    app.constant("gnAPI", $gn);
    
    app.service("gnService", function(gnAPI,$q) {
        this.getPaymentToken = function(cardData) {
            var future = $q.defer();
            gnAPI.ready(function(checkout) {
                checkout.getPaymentToken(
                    cardData,
                    function callback(error, response) {
                       if (error) {
                           future.reject(error);
                       } else {
                           future.resolve(response);
                       };
                    } 
                );
            });
            return future.promise;
        };
    });
    

    Then to use in a controller:

    var cardData = {
        brand: 'visa', 
        number: '4012001038443335', 
        cvv: '123', 
        expiration_month: '05',
        expiration_year: '2018'
    };
    
    gnService.getPaymentToken(cardData)
      .then(function (response) {
        console.log(response);
    }).catch(function (error) {
        console.log(error);
        throw error;
    });
    

    By using the AngularJS $q service to create a $q service promise, the external asynchronous API will properly integrate with the AngularJS framework and its scope digest cycle.

    For more information, see AngularJS $q Service API Reference.