Using Angular to make an API call within a JavaScript function

I am facing an issue when trying to call an API in a JavaScript function as shown below. The injected services (subService) and defined variables (formData) are not recognized in the JavaScript function, resulting in an error of undefined addSub. How can I resolve this problem and successfully call the API in the JavaScript function?

Your help and guidance on this matter would be greatly appreciated.

HTML

<button class="btn" (click)="initializePayment(item.id,item.price)">click here</button>

TS

 formData: any;
      loading: boolean = false;

      constructor(
        private subService: SubService,
      ) { }

        initializePayment(sid,amount: number) {
            this.loading = true;
            const paymentHandler = (<any>window).StripeCheckout.configure({
              key: this.stripeKey,
              locale: 'auto',
              token: function (stripeToken: any) {
                console.log({stripeToken});
                const sToken = stripeToken.id;
                this.formData = new FormData();
                this.formData.append('id', this.id);
                this.formData.append('s_id', sid);
                this.formData.append('stripeToken', sToken);
        
                this.subService.addSub(this.formData).subscribe(
                  (response) => {
                    this.loading = false;
                    console.log('resp: ', response);
                    if (response['status'] === true) {
                      this.notifyService.showSuccess(
                        'success!!',''
                      );
                      //window.location.reload();
                      this.router.navigate(['/user']);
                    } else {
                      this.notifyService.showError(
                        'Something went wrong. Please try later!!!',''
                      );
                    }
                  },
                  (error) => {
                    this.notifyService.showError(
                      error,
                      'Oooops Something went wrong. Please try later!!'
                    );
                    this.loading = false;
                  }
                );
                //alert('Stripe token generated!');
              }
            });
          
            paymentHandler.open({
              name: 'test',
              description: 'Upgrade',
              amount: amount * 100
            });
          }
    

Answer №1

Update the function assigned to token by utilizing an arrow function.

token: (stripeToken: any) => {
            console.log({stripeToken});
            const sToken = stripeToken.id;
            this.formData = new FormData();
            this.formData.append('id', this.id);
            this.formData.append('s_id', sid);
            this.formData.append('stripeToken', sToken);
    
            this.subService.addSub(this.formData).subscribe(
              (response) => {
                this.loading = false;
                console.log('resp: ', response);
                if (response['status'] === true) {
                  this.notifyService.showSuccess(
                    'success!!',''
                  );
                  //window.location.reload();
                  this.router.navigate(['/user']);
                } else {
                  this.notifyService.showError(
                    'Something went wrong. Please try later!!!',''
                  );
                }
              },
              (error) => {
                this.notifyService.showError(
                  error,
                  'Oooops Something went wrong. Please try later!!'
                );
                this.loading = false;
              }
            );
            //alert('Stripe token generated!');
          }
        })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting JSON objects into datetime: A step-by-step guide

I am looking for a way to display JSON data in a Kendo chart. Below is the code I have: <head> <meta charset="utf-8"/> <title>Kendo UI Snippet</title> <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019 ...

Shifting hues with every upward and downward movement

I am experiencing a small issue with this JS code... -I have multiple divs that are changing automatically in rows as they move randomly... I want to change the color of the div moving up to green. And for the div moving down, I want to change the colo ...

Customized placement of form fields on an HTML grid determined by the user

My goal is to organize input elements on a grid based on user preferences. After researching, I stumbled upon CSS grids, which seem promising. I am considering creating a CSS grid with r rows and c columns, then using JavaScript to assign input elements t ...

A step-by-step guide on reversing options in the Ant Design Cascader component

By default, the Cascader component's options are nested from left to right. I am looking to have them go from right to left instead. However, I could not find anything in the component's API that allows for this customization. Is it even possibl ...

"Resetting the state of a form in AngularJS2: A step-by

Looking to reset the form state from dirty/touched in angular? I am currently delving into the world of angular2 and working on a form with validation. In my journey, I came across this code snippet: <form *ngIf="booleanFlag">..</form> This ...

Angular 2 combined with Node.js and PostgreSQL

Is there a way to show database data on the front-end of my application? In my app.js file, I have included: app.use('/database', databaseRoutes); Here is the content of my database.js file: const { Pool, Client } = require('pg') co ...

Is it possible to attach a mouse click event to styled text?

Is there a way to specify a mouse click event for an element with a decoration applied to the text, matched with regex? The option to specify a hoverMessage is available, but I would like to find a way to execute a function based on which decorated text ...

Using HTML and CSS to create a Contact Form

Greetings! I have come across this contact form code: /* Custom Contact Form Styling */ input[type=text], [type=email], select, textarea { width: 100%; padding: 12px; border: 1px solid #555; margin-top: 6px; margin-bottom: 16px; resize: v ...

The dragging and dropping feature for HTML input type="file" is not functioning properly in Edge and IE11

I've developed an Angular app using this sample where I have included only an input control on the screen. Within my project, I constructed a custom file-uploader component. While I am able to drag and drop files in Chrome, I encountered issues with d ...

The Observable<ArrayBuffer> type does not have a property map

I encountered an issue while upgrading from Angular v4 to Angular v6. I was in the process of replacing Http and HttpModule with HttpClient and HttpClientModule. As a result, I imported HttpClient from @angular/common/http in a service to fetch results fro ...

What is the best way to enable external events for Fullcalendar in an Angular environment?

Struggling to integrate external events with Fullcalendar and Angular. Admittedly, I am new to Angular and there are aspects that still elude me. Fullcalendar provides a guide on setting up with Angular, available here. Initially, I managed to set up the ...

Can someone help me figure out how to simulate an express middleware class method using jest and supertest?

I'm facing some challenges trying to achieve the desired outcome when mocking a method in a class using jest and supertest. I'm specifically looking for a solution that can help me bypass the verifyAuthenticated method with a mocked version in or ...

How to arrange three buttons in a row using CSS styling

After reviewing similar issues posted by others, I have not found a solution to my problem. Despite trying the suggested solutions, I am unable to center two buttons representing different departments on my webpage. Here is my source code: <script ...

What is the reason behind the shifting behavior of e.currentTarget when using event delegation in jQuery?

Click here for the code snippet <div id="container"> <button id="foo">Foo button</button> <button id="bar">Bar button</button> </div> $('#container').on('click', function(e) { var targ ...

What is the best way to display data in the User Interface when data is being received through the console in AngularJS?

I have created an HTML file and the corresponding controller logic for this page. I can see the data in the console, but it's not displaying on my UI. <div id="panelDemo14" class="panel panel-default" ng-controller="NoticeController"> < ...

Angular 10 Error: API Module Redundancy Detected

My current issue lies with the ApiModule generated by Swagger. Despite providing it only once in my AppModule, it appears to be created twice, causing the application to fail due to a constructor guard: export class ApiModule { public static forRoot(co ...

Ways to verify whether an array contains any of the specified objects and then store all those objects in Supabase

Perhaps the title of my question is not very clear, but I find it difficult to summarize in just one line. To provide context, it would be best to see the JavaScript query I'm making for Supabase and its response. The data: [ { title: 'Th ...

``There is an issue with the onsubmit property that prevents the opening of

I have encountered an issue with my forms that has me stumped. Despite searching online for help, I can't seem to figure out why my implementation is not working as intended. The concept is straightforward. I've embedded a form within a JSP page ...

How come the hook keeps triggering endlessly in a loop when I try to pass the updated props?

I've encountered an issue with a custom hook I created for making HTTP requests. The problem is that the request seems to be firing in an endless loop, and I'm unsure of what's causing this behavior. My intention is for the request to only t ...

How can you verify the presence of an object containing specific data within an array using JavaScript?

Currently, I am working with the Vue programming language and have some demo code to showcase: <template> <button @click="checkInList">Check</button> </template> <script> import { ref } from "@vue/reactivity& ...