What is the best way to obtain the actual name of a component's method?

Just to clarify the next part: payU serves as the Internet payment operator

I'm currently facing a significant challenge when it comes to integrating my Angular app with payU payments. Due to security reasons, I have opted not to store or pass credit card data and instead decided to use a widget.

The first hurdle I encountered was how to properly place the widget in the code. According to the documentation, the script should be inserted in the following manner:

<script
    src="https://secure.payu.com/front/widget/js/payu-bootstrap.js"
    pay-button="#pay-button"
    merchant-pos-id="145227"
    shop-name="Nazwa sklepu"
    total-amount="9.99"
    currency-code="USD"
    success-callback="test"
    sig="250f5f53e465777b6fefb04f171a21b598ccceb2899fc9f229604ad529c69532">
</script>

As you may already be aware, inserting a script in this way is not possible within Angular. So, I came up with a workaround:

    ngAfterViewInit(): void {
        this.script = document.createElement('script');
        this.script.setAttribute('src', 'https://secure.payu.com/front/widget/js/payu-bootstrap.js');
        this.script.setAttribute('pay-button', '#pay-button');
        this.script.setAttribute('merchant-pos-id', '145227');
        this.script.setAttribute('total-amount', '9.99');
        this.script.setAttribute('currency-code', 'USD');
        this.script.setAttribute('success-callback', 'test');
        this.script.setAttribute('sig', '4752ce2b163684a9c27cc0923ad46068c04da5d34329f5669ce73dcf96394558');
        this.renderer.appendChild(this.el.nativeElement, this.script);
    }

I understand that this is not a perfect solution (if you have a better approach, please feel free to share in the comments).

However, the major issue lies in passing the name of the callback function to the success-callback attribute. I created a function in my component like so:

    test(arg: any) {
        console.log(arg);
    }

But I struggled to retrieve the name. I attempted:

this.script.setAttribute('success-callback', this.test.name);

however, the property name remained empty. Is there a straightforward way to obtain the actual method name (after TypeScript compilation) in my component?

On a side note,

Although adding a simple JavaScript script to index.html and providing its name works, I need to access a service within my function.

I am utilizing Angular v7.

Answer №1

Breakdown:

To start dissecting the script, let's first understand how it operates. The script is integrated into the global namespace, meaning that the success callback points to a function named 'test' within your code snippet above.

For the success callback to access the 'test' function within the angular component, we must establish a connection in the global namespace of your application.

Incorporating into your component:

import {NgZone} from '@angular/core';

constructor(private zone:NgZone){
    window.callbackComponentRef = {
      testFn: (args) => {
        this.zone.run(() => { this.test(args); })
      } 
    };
}

test() {
    //Include any desired code here
}

Utilize in the script addition section

this.script.setAttribute('success-callback', 'callbackComponentRef.testFn');

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

Struggling to modify a string within my React component when the state is updated

Having a string representing my file name passed to the react-csv CSVLink<> component, I initially define it as "my-data.csv". When trying to update it with data from an axios request, I realize I may not fully understand how these react components w ...

Error: *** is not a valid function within a React element

I am encountering an issue while attempting to call a function of an object passed as an argument in a React component's constructor. The error message I receive is: Uncaught TypeError: _this.layout.getWbsLayout is not a function at new Wbs (Wbs. ...

What is preventing me from deleting cookies on Express?

Whenever a new user is registered, the number of cookies just keeps increasing endlessly. userRoutes.js: const { registerUser, loginUser, registerVerify } = require("./userController"); const express=require('express') const router=ex ...

Is there a way to utilize an Angular Material checkbox without any extra gaps or spacing?

Currently, I am working with Angular Material and trying to figure out how to remove the default spacing around the checkbox. The checkboxes in Angular Material are typically surrounded by some space (as shown in the image). Is there a simple way to elimin ...

Using forRoot does not trigger Angular lazy loading functionality

I have implemented a lazy load module that needs to expose providers by utilizing the forRoot convention and returning the following code: @NgModule({ imports: [RouterModule.forChild([ {path: "", component: LazyComponent}, ])], declarations: [La ...

Angular 10 experiences issues with JWT Helper service causing errors

Currently, I'm facing an issue with my Angular 10 project and the latest JWT Helper service. Unfortunately, the app is failing to compile. The error message that pops up reads as follows: ERROR in node_modules/@auth0/angular-jwt/lib/jwthelper.servic ...

Discover the country's three-letter code with the power of HTML and Javascript!

I am in search of a way to determine the location of a user based on the country they are browsing from. I want to achieve this using HTML and Javascript. While researching on stackoverflow, I came across various suggestions to use different API's for ...

"Encountering issues with Instagram embeds.js library failing to load

I've been working on a JavaScript function that loads the HTML embed code for Instagram posts. When the post appears, the photo is replaced by a grey background and the Instagram logo. Even though the post contains other information like hashtags, tim ...

Controlling multiple bx-sliders with a single pager using only JavaScript

Is there a way to control 3 sliders using the same pager? I attempted to use the following code but it did not work: <script language="javascript"> $('.mobile_left_mble,.mobile_right_mble,.text_btn').bxSlider({ //pagerCustom: '#bx- ...

If the functionality is not behaving correctly following the recent update to Angular 17

There seems to be a problem with the @if statement in this code snippet. When isLoggedIn is interpolated outside of the if block, it evaluates as true. However, within the if block, it evaluates as false and always displays 'Login'. If there are ...

What is the best method to trigger a bootstrap modal window from a separate component in Angular 8?

I have successfully implemented a bootstrap modal window that opens on a button click. However, I am now facing difficulty in opening the same modal window from a different component. Below is the code I have tried: <section> <button type=&quo ...

Avoid requesting Chrome Camera permission if it has already been granted during a previous WebRTC call

Our web-conference application utilizes a Flash client for video and audio communication. Video is handled through the Red5 Media Server, while audio is managed using WebRTC. When attempting to access the microphone or camera in Flash, users are required ...

Is there a way to unselect a button in Angular?

I have a set of buttons representing different categories. When I click on a button, it displays a card with relevant information. <app-category-button [label]='category.name' [isSelected]='category.id === (selectedCategoryId$ | asy ...

I need assistance with retrieving the value in a password field using JavaScript. I've been stuck on this issue all morning and would greatly appreciate any

Currently utilizing document.getElementById("password").value for retrieving the input value of the password field. Seeking assistance! Additionally, the form contains an action="authenticate_signup.php" Encountering an issue where the password field va ...

Creating a route provider tailored to specific user roles

I have a rather straightforward requirement. There are 3 different User Roles: CATUSER LICUSER ALLUSER The User Role value is stored in the $rootScope.userRole variable. The User Role is predefined before the AngularJS application starts as the Angula ...

AngularJS UI Router: Best Practices for Including the Controller Script

I have created a basic AngularJS single page application that uses UI Router to navigate between two views. When the user clicks on the Home link, they should see a line of text. Similarly, clicking on the About link should display some text as well, but i ...

The disappearance of HTML DOM nodes event

When I relocate certain DOM nodes from one context to another, some of the child nodes end up losing their event listeners. HTML <div><lots of nested nodes .../><div> <div> <div> <div#newNode></div> < ...

Optimizing Three.js for better performance

Recently, I delved into working with three.js and webgl for a personal project. My goal was to develop a wardrobe model based on user input. You can check out the project at this link: Initially, the rendering speed was fast and smooth without Materials a ...

The onClick function is called when I fail to click the button within a React form

I set up a form and I would like to have 2 ways to submit it: One by filling out the input field and pressing enter One by recording voice (using the react-speech-recognition library) However, after adding the second way, the input fi ...

ways to invoke javascript function on body loading

I'm struggling to invoke a JavaScript function when the body loads. Currently, I have the function call on a button but cannot get it to work when added to the body load event. HTML: <body onload="bodyload();"> JavaScript: function bodyload( ...