Search code examples
javascriptangulartypescriptrazorpay

Angular6: Unable to access js variable in template getting async data


I am trying to print the list of banks given by razorpay on the template I get all the bank lists Object in response and save it in a variable banks, but this variable does nothing in the template i.e. I can't see any value

I tried to print below code and I can never see Hello getting print

<h2 *ngIf="banks">Hello</h2>

Below is my snippet from component.ts

ngOnInit() {
    if (this.common.platformCheck()) {
      var razorpay = document.createElement('script');
      razorpay.id = 'razorPay'
      razorpay.src = 'https://checkout.razorpay.com/v1/razorpay.js';
      razorpay.async = true;
      razorpay.type = "text/javascript";
      var scpt = document.getElementsByTagName('script')[0];
      scpt.parentNode.insertBefore(razorpay, scpt);
      razorpay.onload = () => {
        var options = {
          "key": "rzp_test_XXXXXXXXXXX",
          "image": 'https://i.imgur.com/n5tjHFD.png'
        };
        var razorpay = this.windowObj.Razorpay(options);
         razorpay.once('ready', function (response) {
           this.banks= response.methods.netbanking;
          console.log(response.methods);
          console.log(razorpay.methods.netbanking);
          // response.methods.netbanking contains list of all banks
        })
      };
    }
  }

Solution

  •    razorpay.once('ready', function (response) {
           this.banks= response.methods.netbanking;
          console.log(response.methods);
          console.log(razorpay.methods.netbanking);
          // response.methods.netbanking contains list of all banks
        })
    

    The issue is in the function keyword, since the this used inside that function block will be contextual to the function itself, not the component's this. Just change it to this:

       razorpay.once('ready', (response) => {
           this.banks= response.methods.netbanking;
          console.log(response.methods);
          console.log(razorpay.methods.netbanking);
          // response.methods.netbanking contains list of all banks
        })
    

    and it should work, since the this will refer to the component's this, filling the correct component property.

    More readings about ..."this":