The addition operator is not compatible with the given types

Hello, I am currently working on integrating PayPal into an Angular 5 project. The code snippet below shows how I render PayPal buttons using a function:

ngAfterViewChecked(): void {
    if (!this.addScript) {
      this.addPaypalScript().then(() => {
        this.abbonamenti.forEach((item, index) => {
          paypal.Button.render(this.payPalConfig +index, '#paypal-checkout-btn' + index);
          this.paypalLoad = false;
        })
        })
      }
  }

In the above code, different PayPal configurations need to be loaded for each button. Here is an example of such configuration:

payPalConfig = {
  env: 'sandbox',
    client: {
                sandbox:    'AfOCNI-QeZrhkX2lT5e4xY0S2KTfgoDarEXwk4mkK0ge4EoeW25VN5cg5ZlNRrdJrWUctHWBGGbP4d2V',
                production: 'AUiobQL_EOnmPB4ytmb5ZZHbLZT4hXk7UZgMzGwkd8HFIR6qZ5qJZM3JOb91O4y5frw4197ygPyfbor0'
            },
    commit: true,

            // payment() is called when the button is clicked
            payment: function(data, actions) {

              // Make a call to the REST api to create the payment
                return actions.payment.create({
                    payment: {
                        transactions: [
                            {
                                amount: { total: 40, currency: 'EUR' }
                            }
                        ]

            }
                });
            },
    // onAuthorize() is called when the buyer approves the payment
            onAuthorize: function(data, actions) {

                // Make a call to the REST api to execute the payment
                return actions.payment.execute().then(function() {
                    window.alert('Payment Complete!');
                });
            }
  };

However, I am facing issues with concatenation or indexing in the function names. When trying to include '+ index' in the function name, it results in a syntax error. I'm struggling to solve this problem and feeling quite frustrated.

Answer №1

Attempting to use the + operator on an object is not allowed. Please refer to the following line

paypal.Button.render(this.payPalConfig +index, '#paypal-checkout-btn' + index);

The issue stems from this.payPalConfig being treated as an object in the above code snippet.

Solution:

To resolve this error, simply remove the usage of + and index, and pass the object directly like so:

 paypal.Button.render(this.payPalConfig, '#paypal-checkout-btn' + index);

Amendment:

The correct configuration should be as follows:

payPalConfig = new PayPalConfig(PayPalIntegrationType.ClientSideREST, PayPalEnvironment.Sandbox, {
    commit: true,
    client: {
        sandbox: 'yourSandboxClientId',
    },
    button: {
        label: 'paypal',
    },
    onPaymentComplete: (data, actions) => {
        console.log('OnPaymentComplete');
    },
    onCancel: (data, actions) => {
        console.log('OnCancel');
    },
    onError: (err) => {
        console.log('OnError');
    },
    transactions: [{
        amount: {
            currency: 'USD',
            total: 9
        }
    }]
});

For more information, please visit - https://github.com/Enngage/ngx-paypal

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

The FileReader's onload event handler does not seem to be triggering as expected

In short, my issue revolves around reading a csv file from an android device using JavaScript's FileReader. Although my code was functioning properly a month ago, upon revisiting it recently I discovered that the onload function no longer seems to be ...

Is there a way to modify the button exclusively within the div where it was pressed?

I plan to incorporate three buttons in my project (Download, Edit, and Upload). Upon clicking the Download button, a function is triggered, changing the button to Edit. Clicking the Edit button will then change it to Upload, and finally, clicking the Uplo ...

Combine all the missing observables in RxJS into a single array

In my code, I am creating a NavBar with items that may require fetching extra information from an API and adding it to the subtitle field. I want to transform this into an Observable<NavItem[]> so that it can be rendered using an Async Pipe. Curren ...

After subscribing, my Angular template fails to refresh

Currently, I am facing an issue with my Angular 17 project where the data fetched from the API is not updating the template. This means that despite receiving the data, I am unable to display it on the page. The code snippet below shows the service compon ...

Encountered an npm error while attempting to start an Angular project

When attempting to run my project using ng serve -o, a warning message popped up on the screen stating: Your global Angular CLI version (15.2.2) is higher than your local version (15.0.4). The local Angular CLI version will be used. To disable this warnin ...

The triggering of Angular Change Detection does not occur when using nested ngFor loops

Currently, I'm deeply engrossed in a substantial Angular project that utilizes NgRx Store. One interesting feature of the app is an infinite scrolling list that displays skeleton items at the end, which are later replaced by real items once the reques ...

Challenge with Routing in Angular 2

I'm dealing with a route setup like this: path: 'something/:id/somethingElse' In my header.component.html, I need to include a link to this page. I tried the following approach: <a routerLink="['something',myIdThatIsDynamicO ...

Updating the node startup file with Visual Studio 2015 using NodeJS/Typescript

Encountering a persistent error: Error Code: TS5055 Cannot write file C:/project/dir/server.js' because it would overwrite the input file. Project: TypeScript/JavaScript Virtual Projects Even after renaming my entry filename to nodeserver.js, the ...

Components in Angular 4 that are loaded dynamically using attribute directives are enclosed within a <div> element

My goal is to dynamically generate components based on the configuration options, specifically creating a toolbar with different "toolbar items". Following the Angular guide at: https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html, I h ...

Encountered an issue with Angular Material sidenav: The synthetic listener @transform.start was found

Click here to visit the StackBlitz link Encountering an issue while attempting to utilize the material side nav. Error message: preview-29b0f46fcc27b310236ab.js:1 ERROR Error: Uncaught (in promise): Error: Found the synthetic listener @transform.start. P ...

Breaking down arrays in Typescript

Let's say I have an array like this: public taskListCustom: any=[ {title: 'Task 1', status: 'done'}, {title: 'Task 2', status: 'done'}, {title: 'Task 3', status: 'done'}, {title: 'Task ...

The patchValue() function in FormGroup does not fire the input event

In my code, I have a FormGroup dedicated to credit card inputs. To format the inputs, I'm using a directive with the selector 'appCreditCardFormat'. Here's a simplified version: <input formControlName="cardNo" appC ...

Tips on preventing the need to redeclare property types in React constructor with Typescript

Imagine having a class structured like this: class PeopleByTag extends React.Component<RouteComponentProps<{ tag: string }> In order to perform actions in the constructor, such as fetching data, you typically need to define a props parameter. Ho ...

What is the correct location to import a custom theme in MUI for Next.js?

I am currently working on a React/Next.js project and I need to customize the colors using MUI. After discovering createTheme(), I realized that the project is written in Typescript. Should I create a separate file with the following code? And where shou ...

Retrieve the component when there is a change in the variable in Angular versions greater than 4

When invoking the ngx-ebar-treemo component in my main component, I use the following syntax: <ngx-ebar-treemo *ngIf="type=='Bar' && graphic" type1="{{type1}}" type2="{{type2}}"></ngx-ebar-treemo> I need to call this compone ...

Using Angular to pass an index to a pipe function

Currently, I am attempting to incorporate the *ngFor index into my pipe in the following manner: <td *ngFor="let course of courses | matchesTime:time | matchesWeekday:i ; index as i">{{course.courseName}}</td> This is how my pipe is structure ...

Embedding an Iframe in Angular 2 directly from the database

Looking for assistance with iframes in Angular 2. Initially, embedding an iframe directly into a component's template functions correctly. <iframe src='http://plnkr.co/edit/zZ0BgJHvQl5CfrZZ5kzg?p=preview | safeUrl' allowtransp ...

execute the function once the filereader has completed reading the files

submitTCtoDB(updateTagForm:any){ for(let i=0;i<this.selectedFileList.length;i++){ let file=this.selectedFileList[i]; this.readFile(file, function(selectedFileList) { this.submitTC(updateTagForm,selectedFileList); }); } } } ...

Identify the nature of the output received after dispatching

I'm developing a functional component within the realm of Redux, and I have configured it to return specific values for a particular action. The new value being returned is derived from a Promise, meaning that if the type is designated as "Ival," the ...

Tips for creating dynamic amd-dependencies in TypeScript

Is there a way to dynamically load a Javascript language bundle file in Typescript based on the current language without using static methods? I want to avoid having to use comments like this for each bundle: /// <amd-dependency path="<path_to_bund ...