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

Vue cannot detect the component that is provided by my plugin

This unique plugin, currently only includes a single component (coded in TypeScript): import _Vue, { PluginObject } from "Vue"; import MyComponent from "./MyComponent.vue"; const VuePlugin: PluginObject<void> = { install(Vue: typeof _Vue): void { ...

Understanding the Relationship Between Interfaces and Classes in Typescript

I’ve come across an interesting issue while working on a TypeScript project (version 2.9.2) involving unexpected polymorphic behavior. In languages like Java and C#, both classes and interfaces contribute to defining polymorphic behaviors. For example, i ...

Issue with Angular Reactive form: Checkbox checked property not binding correctly when the page initially loads

Looking to achieve Two-way data binding of Checkbox in Angular Reactive forms. After checking the checkbox, I am updating the 'isdateChkd' variable and storing it in the state. Despite the variable being set to TRUE, the checkbox does not get aut ...

Error: Cannot find definition of Chart in conjunction with primeNg and angular 4

An error occurs when I remove the following line from my index.html file <script src="node_modules/chart.js/dist/Chart.js"></script> Is it possible to eliminate this line from index.html and instead include the equivalent line in my systemjs. ...

Tips and techniques for updating the form value in Angular 4 Material while maintaining binding characteristics

import {Component,ViewChild} from '@angular/core'; import {NgForm} from '@angular/forms' @Component({ selector: 'checkbox-configurable-example', templateUrl: 'checkbox-configurable-example.html', styleUrls: [& ...

What is the process of encapsulating a callback function within another callback function and invoking it from there?

Here is the code snippet I am working with: var me = this; gapi.auth.authorize({ client_id: client, scope: scope, immediate: true }, function (authResult: any) { if (authResult && !authResult.error) { me ...

Combining all code in Electron using Typescript

I am currently working on developing a web application using Electron written in Typescript and I am facing some challenges during the building process. Specifically, I am unsure of how to properly combine the commands tsc (used to convert my .ts file to ...

Delay the execution until all promises inside the for loop are resolved in Angular 7 using Typescript

I am currently working on a project using Angular 7. I have a function that contains a promise which saves the result in an array as shown below: appendImage(item){ this.imageCompress.compressFile(item, 50, 50).then( result => { this.compressedI ...

Typescript: Retrieve an interface containing properties that are found in interface A, but not in interface B

I am currently developing a mapper that will facilitate the translation between a serialized entity state and a form state. In the context of two given interfaces A and B, I am exploring ways to derive a third interface C that includes properties present ...

The express application's GET route is causing a "Cannot GET" error to be thrown

I am managing different types of pages: the main root page (/) today's chapter page (/929 OR /929/) which eventually redirects to /929/<CHAPTER> where <CHAPTER> is a natural number between 1 to 929 individual chapter pages (/929/<CHAP ...

Attempting to access jQuery from an external JavaScript file within the Ionic 5 framework

Currently, I am working on an Ionic app with Angular. I want to call my JavaScript function when the document is ready in the JS file, but I keep encountering an error. Here is my watch.page.html: <ion-content> <div class="videoContainer&qu ...

Debugger for Visual Code unable to locate URL in Microsoft Office Add-in

I recently installed the Microsoft Office Add-in Debugger VS code extension, but I'm having trouble getting it to work despite following the instructions. Every time I try, an error message pops up: Upon inspecting my launch.json file, I found this U ...

The error code TS2345 indicates that the argument type 'Event' cannot be assigned to a parameter type 'string'

Hello, I'm a newcomer to utilizing Angular and I'm struggling to identify where my mistake lies. Below is the TypeScript code in question: import { Component } from '@angular/core'; @Component({ selector: 'app-root' ...

Tips for adjusting the radio button value similarly to a checkbox in Angular 2 using *ngFor

my checkbox and radio button implementation: <input id="{{k.group_name}}_{{i}}" name="{{k.group_name}}" type="checkbox" class="hide" name="{{k.group_name}}" [value]="m.details" (change)="change($event, m , k.item_ingredient_group_key,false,k.maximum)"& ...

How can one trigger a service method in nestjs through a command?

I am looking to run a service method without relying on API REST - I need to be able to execute it with just one command ...

What is the best way to wrap `useFetch` in order to leverage reactivity?

When I wrap useFetch() as a composable to customize the baseURL and automatically set an authentication token, I encounter reactivity issues when calling the composable within a component without using the await keyword. Typically, I would call const { dat ...

Fix React/Typescript issue: Exported variable conflicts with name from external module

I am encountering a perplexing issue when using React with Redux and Typescript. The error message I am receiving is unfamiliar to me, and I am unsure how to resolve it. The error states: Exported variable 'rootReducer' has or is using name ...

I'm currently working on building a form with the Angular framework, but I'm facing a challenge in displaying all the

I am having trouble with my Angular form as I am only able to display two fields when the page is loaded. Code snippet from Component.html: <div class="card m-3"> <div class="card-body"> <form [formGroup]="surveyFor ...

Creating Typescript packages that allow users to import the dist folder by using the package name

I am currently working on a TypeScript package that includes declarations to be imported and utilized by users. However, I have encountered an issue where upon publishing the package, it cannot be imported using the standard @scope/package-name format. I ...

Encountered an issue in React and Typescript where the argument type is not compatible with the parameter type 'EventListenerOrEventListenerObject'

One challenge I am facing is integrating Typescript into my React project: componentDidMount() { document.addEventListener('mousemove', this.handleMouseMove); } private handleMouseMove = (e: React.MouseEvent<HTMLElement>) => { appS ...